【发布时间】:2015-07-16 08:00:12
【问题描述】:
我想将一个类的成员存储到一个向量中。在我的课堂上,我有一些私有变量,我通过常量指针访问它们,以防止它们被更改 (see this post)。问题:当我在循环期间将类的实例添加到向量中并随后访问它们时,所有元素似乎都是最后添加的元素。这是一个 MWE:
#include <iostream>
#include <vector>
using namespace std;
class myClass {
private:
int x_;
void init(int x) {
x_ = x;
}
public:
const int &x;
myClass(int x) : x(x_) {
init(x);
};
};
int main(int argc, const char * argv[]) {
vector<myClass> myVector;
// Does not work
for (int j=0; j<3; j++) {
myVector.push_back(myClass(j));
}
for (int j=0; j<3; j++) {
cout << "1st attempt: " << myVector.at(j).x << endl;
}
myVector.clear();
// Works
for (int j=0; j<3; j++) {
myVector.push_back(myClass(j));
cout << "2nd attempt: " << myVector.at(j).x << endl;
}
myVector.clear();
// Works also
myVector.push_back(myClass(0));
myVector.push_back(myClass(1));
myVector.push_back(myClass(2));
for (int j=0; j<3; j++) {
cout << "3rd attempt: " << myVector.at(j).x << endl;
}
return 0;
}
Ovious 问题:我做错了什么,我可以解决它吗?
【问题讨论】:
-
我的直觉是它与你创建的对象被复制有关,成员变量
x将引用由例如创建的临时对象的x_成员变量。myClass(j)。换句话说,尝试创建一个复制构造函数,以确保x变量引用自己的x_变量。 -
你可以发布输出吗?