-1

我有这段代码,在我的脑海中,它收到了一个名为 Vehicle 的项目,它必须将它存储在一个名为 Node.js 的数组中。这是与这部分程序相关的代码:

void Table::process(Vehicle v, int cont) {
    char a='A'+cont;
    putVehicle(a,v);
    Node.a_v[cont]=v;
    if(cont==0) a_surt=v.rowVehicle();
}

这就是我在 Table.h 的私有部分拥有数组的方式:

struct Node{
    Vehicle a_v;
};

我得到的错误是:

error: expected primary-expression before '.' token

我有我需要的包含,但每次我输入这个:Node.a_v它给了我那个错误。有什么建议吗?

4

4 回答 4

4

如果你想使用一个结构,你需要Node在使用它之前声明一个。此外,结构需要包含一个数组(或者更好的是,查看向量以获得更大的灵活性)。

struct Node {
    Vehicle[10] a_v; // 10 is max number of Vehicles in array
};

Node myNode;
myNode.a_v[cont] = v;

请记住,如果您想保留它Node并在其中放入更多内容,则需要在正确的范围内声明它。例如,要让你的process函数将 a 添加VehicleNode存在于函数之外的a 中process,你可以这样:

void Table::process(Node n, Vehicle v, int cont) {
    char a = 'A'+cont;
    putVehicle(a,v);
    if (cont < 10) {
        n.a_v[cont] = v;
    }
    if (cont == 0) a_surt = v.rowVehicle();
}

看起来你只是想使用一个数组。在这种情况下,您正在寻找这样的东西:

// This would go somewhere in your program. Again, 10 is just an example.
Vehicle vehicleArray[10];

// Send this array to this function
void Table::process(Vehicle[] vArray, Vehicle v, int cont) {
    char a = 'A'+cont;
    putVehicle(a,v);
    if (cont < 10) { // In a real program, don't hard-code array limits.
        vArray[cont] = v;
    }
    if (cont == 0) a_surt = v.rowVehicle();
}
于 2013-04-26T13:32:36.650 回答
3

您应该使用Nodeobject 来访问a_v变量。这条线

Node.a_v[cont]=v;

是不正确的。你应该这样做:

Node n;
n.a_v[cont]=v;
于 2013-04-26T13:32:32.277 回答
2

每次我输入这个: Node.a_v 它给了我那个错误。

Node是一种类型;类型定义了对象的结构,但它们没有自己的字段(static字段除外,它们同时属于所有实例;无论如何,它们的访问方式不同)。

为了使用.or->运算符,您需要一个a的实例Node,如下所示:

Node x;
x.a_v = ...

但是,在您的情况下,尚不清楚Node实例应该来自哪里。为了访问它们,您需要将它们作为参数传递,或者使它们静态/全局可用(不推荐)。

于 2013-04-26T13:33:44.663 回答
0

好的,所以 Node 不是您的数组的名称。它是应该包含数组的用户定义类型的名称。但是,您的节点不包含数组。它包含一辆车,名为 a_v。我假设 a_v 应该代表一个车辆数组。因此,您需要分配数组。像这样的东西:

struct Node {
   Vehicle a_v[AMOUNT];
};

如果您在编译时不知道您希望数组有多大,则必须动态分配它们,如下所示:

struct Node {
   Vehicle* a_v;
   Node() {
      a_v = new Vehicle[AMOUNT];
   }
};

如果它是动态分配的,那么它也必须被释放:

struct Node {
   Vehicle* a_v;
   Node() {
      a_v = new Vehicle[AMOUNT];
   }
   ~Node() {
      delete[] a_v;
   }
};

如果它是动态分配的,则需要添加用于复制或禁用复制的规定:

struct Node {
   Vehicle* a_v;
   Node() {
      a_v = new Vehicle[AMOUNT];
   }
   ~Node() {
      delete[] a_v;
   }

   // Disable copies (with C++11 support):
   Node(const Node&) = delete;
   Node& operator=(const Node&) = delete;

   // Disable copies (without C++11 support) by making them private and not defining them.
   private:
   Node(const Node&);
   Node& operator=(const Node&);
};

然后要访问其中一辆车,您需要这样做:

Node n;  // Declare a node, which contains an array of Vehicles
n.a_v[cont] = v;  // Copy a Vehicle into the array of Vehicles

但是请注意,如果您在此函数中声明 Node 实例,则它是本地的,并且一旦您的函数结束,它将超出范围。如果您希望 Node 实例在函数调用之后持续存在,则需要将其声明为 Table 的成员。

class Table
{
   private:
      Node n;
};

最后,正如其他人所建议的,我强烈建议您阅读 C++ 书籍来学习 C++。我个人推荐的是这本书(第 5 版,不要买第 6 或第 7 版——那些版本的作者很糟糕)。

于 2013-04-26T13:58:25.500 回答