我写了下面的代码,我期望得到 5个 6个 6个 6,但我得到的是 5 6 5 0。似乎“val”一开始就正确地获得了引用,但后来它丢失了。有人知道我的错误在哪里吗?
class Count {
public:
void add() {
val++;
}
void print() {
cout << val << endl;
}
Count(int c): val(c) {
}
private:
int &val;
};
int main() {
int c = 5;
Count teste(c);
teste.print();
teste.add();
teste.print();
cout << c << endl;
teste.print();
return 0;
}
最佳答案
你的构造函数应该通过引用而不是值来获取参数。
关于c++ - 引用的初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5179553/