У меня проблема с другой программой, но я попытался упростить ее с помощью этой программы. Я не могу установить имя оружия через 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);
};
Оружие. 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;
}