我通常用 C 工作,但现在我必须用 C++ 工作。我有一个大文件,有很多重复,因为我目前无法循环遍历 dir_x 到 dirx_z。
1. 有没有办法使此类中的元素像数组一样可寻址?我在最后一行举了一个例子。
2.我目前指的是
Node * dir_x;
作为链接,但真实姓名是什么,以便我可以用谷歌搜索?
class Node {
public:
Node(int x, int y, int z){
//Will be initialized to point to the next Node (neighbor)
//So will be holding elements of this same class!
dir_x = NULL;
dir_y = NULL;
dir_z = NULL;
}
//These are "links", but does anybody know the name to google it?
Node * dir_x;
Node * dir_x;
Node * dir_x;
};
//Code snippet of a function:
//current would be the node to traverse through the collection
Node * current = someNode;
//together with next
Node * next = NULL;
//Here the next node is actually set
next = current->dir_x;
//But I would like a generic way like below
//to reduce code duplication by about a third:
next = current->dir[i];
最佳答案
欢迎使用 C++。您必须自己用 C 构建的许多东西都是 C++ 标准库的一部分。强烈建议使用这些组件而不是构建您自己的组件。在这种情况下,您应该使用 std::list
而不是将所有时间和脑力浪费在重新发明已经完善了一百万次的轮子上。
关于你的问题,
//But I would like a generic way like below
//to reduce code duplication by about a third:
next = current->dir[i];
您可以在Node
类上实现operator[](size_t)
。我猜应该是这样的:
class Node
{
public:
Node * mLeft;
Node * mRight;
Node& operator[] (size_t i)
{
if (!i)
return *this;
return (*mRight)[i-1];
}
};
当然这只是一个说明。您需要自己做很多工作来处理范围检查、异常安全等问题。
关于c++ - 我可以在类声明中声明一个数组,稍后该数组将填充该类的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566762/