【发布时间】:2014-02-04 09:47:26
【问题描述】:
可能是愚蠢的问题,但我找不到答案(即使在这里)。
我已将所有课程拆分为单独的文件 (cpp+h)。我有像getValue() 和setValue() 这样的方法。我有一个名为 Player 的类(这基本上是具有整数个变量的数据库)。我创建了一个名为 player (Player *player = new Player;) 的对象。现在我需要从任何其他类(在另一个文件中分离)访问这个对象。问题是我什至无法访问getValue() / setValue() 方法。
我需要的是类似于 Delphi From1.player.item[0]=3 从表格 2 中访问,记录播放器的地方。
更新:
这是我的代码:
播放器.cpp
#include "player.h"
#include "gameform.h"
Player::Player()
{
}
void Player::check(){
//I should be able to check if player dead or not from my Battle class
}
播放器.h
#ifndef PLAYER_H
#define PLAYER_H
class Player
{
public:
Player();
void check();
};
#endif // PLAYER_H
Battle.cpp
#include "battle.h"
#include "player.h"
#include "game.h"
Battle::Battle()
{
}
void Battle::hit(){
//if I hit I should check am I dead yet
player.check();
}
这就是 Player 在 Game 类中声明的方式(现在):
Player *player = new Player;
在任何函数之外,就在课堂上。
其中玩家是对象,在 Game 类中创建。一切都是公开的。
*我什至尝试在 main.cpp 中创建对象(在 main() 函数内外),但没有任何效果,奇怪 =/
这是 github "temp" 分支,正在编译和工作。但是如何访问播放器? :)
https://github.com/ewancoder/game/tree/temp
UPD:另一个愚蠢的问题:如果我希望在我的 1 类函数中负责打开文件和另一个 - 用于编辑和关闭文件,如果无法从另一个函数读取变量,我该怎么做?
【问题讨论】:
-
你遇到了什么错误?
-
发布您的
Player声明。看来您的方法都是私有的。访问this很奇怪。你的意图是什么? -
这是
player.check(),而不是player.check。这是一个不带参数的函数,由()表示。 -
player是否在Battle类中声明?你可以为Battle发布你的班级声明吗? -
玩家在 Game 类中声明(它包含在 Battle 中),并且 Battle 应该能够访问 Game。 Battle.h 看起来就像 player.h,只是有自己的名字。
标签: c++ function class methods