1

我正在尝试使用向量创建一个类数组,但我认为实例化数组时语法错误。我得到的错误是:

error: request for member 'setX' in objects[0], which is of non-class type 'std::vector'

#include <iostream>
#include <vector>

using std::cout;

class A {
    public:
        void setX(int a) { x = a; }
        int getX() { return x; }
    private:
        int x;
};

int main() {

    std::vector<A> *objects[1];

    objects[0].setX(5);
    objects[1].setX(6);

    cout << "object[0].getX() = " << objects[0].getX() << "\nobject[1].getX() = " << objects[1].getX() << std::endl;
}
4

4 回答 4

5
std::vector<A> objects; // declare a vector of objects of type A
objects.push_back(A()); // add one object of type A to that vector
objects[0].setX(5); // call method on the first element of the vector
于 2012-08-18T01:05:45.887 回答
3

使用星号和方括号,您声明的是指向向量的指针数组,而不是向量。你std::vector<T>不需要方括号或星号:

std::vector<A> objects(2); // 2 is the number of elements; Valid indexes are 0..1, 2 is excluded

objects[0].setX(5); // This will work
objects[1].setX(6);

编译器认为您试图调用setXavector的原因是方括号运算符(由向量重载)也是数组或指针上的有效运算符。

于 2012-08-18T01:06:31.727 回答
1

数组和std::vector是两种完全不同的容器类型。数组实际上是固定大小的内存块,其中std:vector对象是动态顺序容器类型,这意味着它可以在运行时动态“增长”和“缩小”,对象本身管理内存分配它拥有的对象。它们明显的相似之处在于都可以访问复杂度为 O(1) 的成员,并且可以使用括号语法来访问成员。

您想要的是以下内容:

int main() 
{

    //make a call to the std::vector<T> cstor to create a vector that contains
    //two objects of type A
    std::vector<A> objects(2);

    //you can now access those objects in the std::vector through bracket-syntax

    objects[0].setX(5);
    objects[1].setX(6);

    cout << "object[0].getX() = " << objects[0].getX() << "\nobject[1].getX() = " << objects[1].getX() << std::endl;

    return 0;
}
于 2012-08-18T01:05:46.120 回答
-1

在这里,您所做的是定义一个包含 1 个std::vector * 类型元素的数组,您可能需要先阅读有关向量数组的更多信息。

定义它的正确方法是:

std::vector<A> objects(2);

或使用指针,如果这是你打算

std::vector<A*> objects(2);
objects[0] = new A();
objects[1] = new A();
于 2012-08-18T01:13:01.053 回答