试图修改对象通过get / set方法的类。我不明白如何变化值仅仅只有使用get / set方法。
预期输出: “输出:89”。
实际的输出:“输出:0”
#include<iostream>
using namespace std;
class TestClass{
public:
int getValue() const{
return _value;
}
void setValue(int value) {
_value = value;
}
private:
int _value;
};
class A{
public:
TestClass getTestClass() const{
return _testClass;
}
void setTestClass(TestClass testClass) {
_testClass = testClass;
}
private:
TestClass _testClass;
};
int main()
{
A a;
a.getTestClass().setValue(89);
cout<<"Output :"<<a.getTestClass().getValue();
}
你返回_testClass
的副本。所以,当你与setValue(89)
修改它,什么都不会发生,因为你只修改是在该行的末尾丢弃的副本。相反,你应该返回引用。
在这里更改此:
TestClass getTestClass() const{
为此:
TestClass &getTestClass() {
你会得到预期的输出。