class modify via set/get methods

2020-03-31 06:50发布

trying to modify object in the class via get/set methods. I can't understand how change value just only use get/set method.

expected output : "Output : 89".

actual output : "Output : 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条回答
走好不送
2楼-- · 2020-03-31 07:16

You're returning a copy of _testClass. So when you modify it with setValue(89), nothing happens because you're only modifying a copy that is discarded at the end of the line. Instead, you should return a reference.

Change this here:

TestClass getTestClass() const{

To this:

TestClass &getTestClass() {

And you get the expected output.

查看更多
Root(大扎)
3楼-- · 2020-03-31 07:38

replace

TestClass getTestClass() const{
    return _testClass;
}

with

TestClass& getTestClass() {
    return _testClass;
}

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.

Some things:

  • please don't use using namespace std; - read here why.

  • please don't name your variables _testClass - go with m_testClass instead. You can read hear about the reasoning.

查看更多
登录 后发表回答