【问题标题】:class modify via set/get methods通过 set/get 方法修改类
【发布时间】:2019-06-30 11:33:08
【问题描述】:

试图通过 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();

}

【问题讨论】:

  • 在 main() 中尝试 a.getTestClass(); 后跟 a.setValue(89);

标签: c++ class constants


【解决方案1】:

替换

TestClass getTestClass() const{
    return _testClass;
}

TestClass& getTestClass() {
    return _testClass;
}

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

一些事情:

  • 请不要使用using namespace std; - 请阅读here 为什么。

  • 请不要将变量命名为 _testClass - 改为使用 m_testClass。你可以阅读hear 了解其中的原因。

【讨论】:

    【解决方案2】:

    您将返回_testClass 的副本。因此,当您使用setValue(89) 修改它时,什么都不会发生,因为您只是在修改在行尾丢弃的副本。相反,您应该返回一个引用。

    在此处更改:

    TestClass getTestClass() const{
    

    到这里:

    TestClass &getTestClass() {
    

    你得到了预期的输出。

    【讨论】:

      猜你喜欢
      • 2011-02-28
      • 1970-01-01
      • 2013-03-09
      • 2013-12-26
      • 2012-12-02
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多