嵌套在 class 中时无法设置成员数据

Can't set member data when nested in a class

我在另一个程序上遇到了这个问题,但我试图用这个程序来简化它。我无法通过 p.getWeaopn().setName("sword"); 设置武器名称当我简单地通过它自己的对象设置它时它工作正常,但是当我尝试通过播放器访问 setter 时它没有设置任何东西。

#include <iostream>
#include <string>
#include "Player.h"
#include "Weapon.h"

using namespace std;

int main()
{
    Player p; // Player contains only a Weapon weapon;
    Weapon w; // Weapon only contains a string name;

    //w.setName("sword"); // this changes the name of the weapon

    p.setWeapon(w);

    p.weapon.setName("sword"); // this also changes the name

    p.getWeapon().setName("sword"); // this is not setting the name. Why?

    // checking if weapon has a name

    if (p.getWeapon().getName().empty())
    {
        cout << "Weapon name is empty!" << endl;
    }
    else
    {
        cout << "Weapon name is " << p.getWeapon().getName() << endl;
    }
}

Weapon.h

#pragma once
#include <string>

using namespace std;

class Weapon
{
private:
    string name;
public:
    string getName();
    void setName(string);
};

Weapon.cpp

#include "Weapon.h"

string Weapon::getName()
{
    return name;
}
void Weapon::setName(string n)
{
    name = n;
}

Player.h

#pragma once
#include "Weapon.h"

class Player
{
private:
    Weapon weapon;

public:

    Weapon getWeapon();
    void setWeapon(Weapon);
};

Player.cpp

#include "Player.h"

Weapon Player::getWeapon()
{
    return weapon;
}
void Player::setWeapon(Weapon w)
{
    weapon = w;
}

Player::getWeapon() returns 每次都是武器的副本,而不是对武器的引用。更改副本中的名称不会更改原始文件中的任何内容。

Weapon Player::getWeapon()

您 return 是武器的副本而不是参考,因此对副本的任何更改都不会影响原始武器。

对于return参考,使用&运算符:

Weapon& Player::getWeapon()
{
    return this->weapon;
}