我可以在类声明中声明一个数组,稍后该数组将填充该类的元素吗?

时间:2013-10-24 13:03:42

标签: c++ arrays class

我通常在C工作,但现在我必须使用C ++。我有一个大文件,有很多重复,因为我当前不能在循环中遍历dir_x到dirx_z。
1.有没有办法让这个类中的元素可寻址,就好像它是一个数组?我在最后一行给出了一个例子。
我现在指的是

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];

2 个答案:

答案 0 :(得分:1)

欢迎使用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];

您可以在operator[](size_t)课程上实施Node。我猜它会是这样的:

class Node
{
public:
  Node * mLeft; 
  Node * mRight; 

  Node& operator[] (size_t i) 
  {
    if (!i)
      return *this;
    return (*mRight)[i-1];
  }
};

当然这只是一个阐述。你需要做很多工作来处理范围检查,异常安全等事情。

答案 1 :(得分:0)

您正在寻找链接列表

    // this would not compile
    Node * dir_x; 
    Node * dir_x; 
    Node * dir_x; 

    // i think you meant
    Node * dir_x; 
    Node * dir_y; 
    Node * dir_z; 

你能做的是

    Node* dir[3]; // now this contains 3 pointers to node elements

您可以随意使用

    Node* node_x = node->dir[0];
    Node* node_y = node->dir[1];
    Node* node_z = node->dir[2];

除非node->dir[2]应该给你第二个节点。哪个也可以实施。