C++ 使用成员对象的 Setter

C++ Using Setter of a member object

我目前正在使用 classes 和对象进行我的第一个项目,我 运行 在 setter 方面遇到了一些障碍。我编了一个例子来说明我正在 运行 遇到的问题(为了简单起见,所有一个文件)。

#include <stdio.h>
#include <iostream>
#include <string>

using namespace std;

class Example1
{
public:
    Example1() { name = "Mike"; }
    Example1(string aName) { name = aName; }
    string GetName() const { return name; }
    void SetName(string newName) { name = newName; }
private:
    string name;
};

class Example2
{
public:
    Example2() : anObj() {}
    Example2(string aName) : anObj(aName) {}
    Example1 GetObj() const { return anObj; }
    void SetObj(string objName) { anObj.SetName(objName); }
private:
    Example1 anObj;
};

int main()
{
    Example2 myObj;
    cout << myObj.GetObj().GetName() << endl;
    myObj.GetObj().SetName("Stan");
    cout << myObj.GetObj().GetName() << endl;
}

输出:

Mike 
Mike

想法是通过使用成员对象的setter方法来改变Example2中的成员对象,但是setter方法似乎没有按我预期的方式工作。

我尝试通过将成员移动到 public(在示例 2 中)并使用点表示法来访问该成员,并且成功地更改了名称。我不确定区别是什么,但是,由于 getter 工作正常,我觉得我使用 setter.

的方式有问题

我试图解决的最初问题是有一个 Game class 和一个 Player class 成员对象。这个想法是玩家可以根据需要更改他们的名字。

感谢任何帮助。谢谢

你所有的getters return一个新对象。不。让他们return一个常量&。但是当您修改对象以调用设置器时,您需要一个非 const getter:

const Example1& GetObj() const;
Example1& GetObj();

现在,存储在下面的对象将被更新,而不仅仅是它们的副本。字符串也一样。

您还可以通过使用调试器看到设置器没有在正确的对象上工作的事实。