gpt4 book ai didi

c++ - 创建一组不起作用的类

转载 作者:行者123 更新时间:2023-11-30 01:25:38 24 4
gpt4 key购买 nike

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

错误:请求对象[0]中的成员“setX”,它是非类类型“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;
}

最佳答案

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

关于c++ - 创建一组不起作用的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12014940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com