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

问题描述 投票:-2回答:1

我在另一个程序上遇到这个问题,但是我试图用这个简化它。我无法通过p.getWeaopn()。setName(“ sword”);来设置武器名称。当我只是通过它自己的对象对其进行设置时,它可以正常工作,但是当我尝试通过播放器访问设置器时,它什么也没设置。

#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:


public:
    Weapon *weapon;
    Weapon* getWeapon();
    void setWeapon(Weapon*);
};

Player.cpp

#include "Player.h"

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

c++ class nested setter
1个回答
-2
投票

最佳猜测p.getWeapon()每次都会返回武器的新副本,而不是对武器的引用。更改副本中的名称不会更改原始名称。

© www.soinside.com 2019 - 2024. All rights reserved.