c++ - 如何从另一个类访问函数?

标签 c++ function class methods

可能是个愚蠢的问题,但我找不到答案(即使在这里)。

我已将所有类(class)拆分为单独的文件 (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

战斗.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;

在任何函数之外,就在类中。

其中 player 是对象,在 Game 类中创建。一切都是公开的。

*我什至尝试在 main.cpp 中创建对象(在 main() 函数内外),但没有任何效果,很奇怪 =/

这是 github“临时”分支,正在编译和工作。但是如何访问播放器? :)

https://github.com/ewancoder/game/tree/temp

UPD:另一个愚蠢的问题:如果我希望我的第 1 类函数负责打开文件,而另一个函数负责编辑和关闭文件,如果一个函数无法从另一个函数读取变量,我该怎么做?

最佳答案

我不确定你想要什么,但如果你有这样的类(class):

a.hpp

Class A {
    public:
       void foo();
};

a.cpp

#include "a.hpp"
void A::foo() {}

你可以这样使用它:

b.hpp

#include "a.hpp"
class B {
   public:
      void stuff(A& a);
};

b.cpp

#include "b.hpp"
void B::stuff(A& a) { a.stuff(); }

关于c++ - 如何从另一个类访问函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21548887/

相关文章:

r - 如何编写将输出作为 S3 类返回的函数

c++ - 如何向 socks5 代理服务器添加身份验证?

c++ - SHGetFileInfo 性能问题

javascript - 如何将自定义标量函数按元素应用于 math.js 中的矩阵?

javascript - Javascript 中只存在同一函数的一个实例

python - * : 'instance' and 'float' 不支持的操作数类型

c++ - 使用单个值引用二维数组中的元素

c++ - 删除类型转换指针的最佳方法

r - 在 R 中绘制多个函数

python - 如何使用append()函数扩展Numpy数组类?