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

Can't set member data when nested in a class

本文关键字:设置 成员 数据 嵌套      更新时间:2023-10-16

我在另一个程序中遇到了这个问题,但我试图用这个程序来简化它。我无法通过p.getWeaopn((设置武器名称。setName("剑"(;当我简单地通过它自己的对象设置它时,它工作得很好,但当我试图通过播放器访问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;
}
}

武器.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);
};

播放器.cpp

#include "Player.h"
Weapon Player::getWeapon()
{
return weapon;
}
void Player::setWeapon(Weapon w)
{
weapon = w;
}
Weapon Player::getWeapon()

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

要返回引用,请使用&运算符:

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

Player::getWeapon((每次返回武器的副本,而不是对武器的引用。更改副本中的名称不会更改原始名称。