通过set / get方法修改类 [英] class modify via set/get methods
问题描述
试图通过get / set方法修改类中的对象。我不明白如何仅使用get / set方法来更改值。
trying to modify object in the class via get/set methods. I can't understand how change value just only use get/set method.
预期输出:输出:89。
expected output : "Output : 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 getTestClass() const{
return _testClass;
}
with
TestClass& getTestClass() {
return _testClass;
}
您要返回参考,否则,您只是返回该变量的副本。但是请记住,返回(非const)对类的成员变量的引用不是一种好的设计方法。
You want to return a reference otherwise you are just returning a copy of the variable. But Keep in mind that returning a (non-const) reference to the member variables of a class is not a good design approach.
某些事情:
-
请不要使用
使用命名空间标准;
-阅读这里为什么。
请不要命名变量 _testClass
- m_testClass
代替。您可以阅读听到有关推理。
please don't name your variables _testClass
- go with m_testClass
instead. You can read hear about the reasoning.
这篇关于通过set / get方法修改类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!