通过类设置修改/ get方法

问题描述 投票:0回答:2

试图修改对象通过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();

}
c++ class const
2个回答
0
投票

更换

TestClass getTestClass() const{
    return _testClass;
}

TestClass& getTestClass() {
    return _testClass;
}

你想返回reference否则你只是在返回变量的副本。但是,请记住,返回一个(非const)引用类的成员变量不是一个好的设计方法。

有些事情:

  • 请不要使用using namespace std; - 读here原因。
  • 请不要命名变量_testClass - 与m_testClass去代替。您可以对推理阅读hear

0
投票

你返回_testClass的副本。所以,当你与setValue(89)修改它,什么都不会发生,因为你只修改是在该行的末尾丢弃的副本。相反,你应该返回引用。

在这里更改此:

TestClass getTestClass() const{

为此:

TestClass &getTestClass() {

你会得到预期的输出。

© www.soinside.com 2019 - 2024. All rights reserved.