【发布时间】:2014-09-12 00:55:31
【问题描述】:
我添加了所有代码。
我面临的确切问题是,当我在game.h 文件中创建成员变量private 时,我在game.cpp 文件中收到一个错误,上面写着n p h 都是game.h 的私有成员。在Xcode。
但是当我从命令行编译程序时,它编译得很好,没有错误。
我想了解我是否做错了什么,或者我这样做是否符合标准?
这是 main.cpp
#include "game.h"
int main() {
game g("Female", "Magic", true, 21, 5, 120);
std::cout << "These are the things every game needs to be a game" << '\n';
std::cout << g << '\n';
return 0;
}
游戏.cpp
#include <iostream>
#include "game.h"
std::ostream& operator<<(std::ostream& s, const game& g) {
return s << &g.n << ' ' << &g.p << ' ' << &g.h;
}
这是我的复合类
#include <iostream>
#include "npc.h"
#include "pc.h"
#include "health.h"
class game {
private:
npc n;
pc p;
health h;
public:
game(const npc& init_n, const pc& init_p, const health& init_h):
n(init_n),
p(init_p),
h(init_h)
{}
game(std::string gen, std::string abil, bool use, int lvl, int h, int arm) :
n(gen, abil),
p(use, lvl),
h(h, arm)
{
}
friend std::ostream& operator<<(std::ostream& s, const game& g) {
g.n.output(s);
g.p.output(s);
g.h.output(s);
return s;
}
npc get_n() { return n; }
pc get_p() { return p; }
health get_h() { return h; }
void set_n(npc init_n) { n = init_n; }
void set_p(pc init_p) { p = init_p ; }
void set_h(health init_h) { h = init_h; }
};
这是一个类
#include <iostream>
class health {
private:
int hp;
int armor;
public:
health(int init_hp, int init_armor) :
hp(init_hp),
armor(init_armor)
{
}
public:
void output(std::ostream& s) const { s << "Characters have this amount of hit points "<< hp << " and an armor rating of " << armor << "\n"; }
};
这是一个类
class pc {
private:
bool user;
int level;
public:
pc(bool init_user, int init_level) :
user(init_user),
level(init_level)
{
}
public:
void output(std::ostream& s) const { s << "A player character has at least "<< user << " user and a level of " << level << '\n'; }
};
这是一个类
#include <iostream>
class npc {
private:
std::string gender;
std::string ability;
public:
npc(std::string init_gender, std::string init_ability) :
gender(init_gender),
ability(init_ability)
{
}
public:
void output(std::ostream& s) const { s << "A non player character has a gender of "<< gender << " and an ability of " << ability << '\n'; }
};
【问题讨论】:
-
...你在使用你的getter和setter吗? C++ 不会自动将属性访问转换为 getter 或 setter 调用。
-
显示您遇到问题的代码
-
你的 setter 中的分配是错误的。
-
离题,但最好将 getter 标记为 const;例如:
npc get_n() const { return n; } -
我正在显示我遇到问题的代码。是的,我重新排列了 getter 和 setter。仅当我将其更改为 public 时仍然有效
标签: c++