class modify via set/get methods

2020-03-31 06:53发布

问题:

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();

}

回答1:

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.



回答2:

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.



标签: c++ class const