嵌套在类中时无法设置成员数据
Can't set member data when nested in a class
我在另一个程序中遇到了这个问题,但我试图用这个程序来简化它。我无法通过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((每次返回武器的副本,而不是对武器的引用。更改副本中的名称不会更改原始名称。
相关文章:
- 嵌套在类中时无法设置成员数据
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 聚合初始化,将成员指针设置为同一结构成员
- 在类 (C++) 之外设置 const int 成员变量
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- 自定义 QML QQuick彩绘项目成员锚点未在 qml 中设置为父级
- 如何在C++中将 cin 设置为类的成员函数?
- 将 AlphaMode 成员设置为 DXGI_SWAP_CHAIN_DESC1 会使 CreateSwapChainFo
- 在VS2017中,我们如何在项目成员之间共享编译设置
- 如何为类中可能无法计算的成员设置值
- 如何在没有setter的情况下设置类内部类的成员变量?
- 在运行时为随机分布类成员设置最小和最大边界?
- 是否可以在C++中使用初始化列表设置数组的特定成员?
- 设置成员 GlobalCEFApp->OnWebKit使用函数地址初始化 C++生成器
- 一个线程设置成员,而另一个循环上方 - 是此螺纹 - 不安全
- 有没有办法使用显式实例化按类型设置成员变量
- 为什么不能为类实例设置成员值?
- 构造函数不设置成员变量
- 我可以在构造函数调用之前设置成员变量吗?
- 如何仅设置成员(如果存在)