我正在尝试学习 C++,我想用一个简单的程序将 X 实例的向量初始化为类成员,但是我遇到了分段错误......你能帮忙吗?
#include <iostream>
#include <vector>
class X {
int _x;
public:
X(int i) { _x = i; }
void print() { std::cout << this->_x << std::endl; }
void xAdd() { _x++; }
};
class Y {
std::vector<X*> _x;
public:
Y(int size) : _x(size) {
for (int i = 0; i < size; ++i) _x.push_back(new X(1));
}
void printAll() {
for(unsigned int i = 0; i < _x.size()-1; i++) {
_x[i]->print();
}
}
};
int main(){
Y *y = new Y(5);
y->printAll();
return 0;
}