C++ - 如何调用创建者类/对象

标签 c++ oop memory object parent

我需要调用来自不同类的对象的属性和函数。

这个想法是将“this”作为参数传递给另一个类构造函数。例如:

instance = ClassName(this);

然后做:

ParentClass parentInstance;
ClassName::ClassName(MainApp _instance){
    parentInstance = _instance;
}

但是,我的编译器说 ParentClass 没有命名类型。想法? 另外,我应该使用指针来节省内存吗?怎么办?

提前致谢。


更新:

好的,抱歉耽搁了。这是实际的代码。首先,一个简单的类。

游戏类:

头文件

#ifndef _GAME
#define _GAME

#include "ofMain.h"

class Game{

 public:
  Game();
  ~Game();

  void hi();
};

#endif

cpp文件:

#include "Game.h"
Game::Game(){}
Game::~Game(){}

void Game::hi(){ 
cout << "hi, I'm game! " << endl;
}

然后,我从 MainApp 创建对象: - 头文件相关代码:

#ifndef _MAIN_APP
#define _MAIN_APP

#include "ofMain.h"
#include "Game.h"

class MainApp : public ofSimpleApp{
 public:
  Game game;
};

#endif

cpp文件相关代码:

game = Game();
game.hi();

这显然有效,因为我只是在创建一个该死的对象。然而,问题来自组合。

我可以在构造函数中将主应用程序作为参数传递,我可以通过 game.setParent(this);... 问题是,我什至无法定义变量来存储对应用程序的引用。

例如:(在没有指针或其他任何东西的情况下变得容易/效率低下)

游戏.h:

#define _GAME
#ifndef _GAME

#include "ofMain.h"
#include "MainApp.h"

class Game{
 MainApp app;

 public:
  Game();
  ~Game();

  void hi();
 };
#endif

这会返回一个“没有命名类型”的错误并且声明 class MainApp 会返回一个“不完整的类型”错误

我确定我在做一些愚蠢的事情。


更新 2:

该方法的问题是我现在无法调用指向对象的函数。

这是Game.h:

#ifndef _GAME
#define _GAME

#include "ofMain.h"

class MainApp;
class Game{


 public:
  Game();
  Game(MainApp* _app);
  ~Game();

  void hi();

  MainApp* app;
};

#endif

如您所见,应用程序(MainApp 类型)作为参数传递。没关系,MainApp 存在,因为它是前向声明。但是,当我尝试调用应用程序的任何功能时,我无法调用(编译器错误提示 Request for member appHi in .... which is non-class type 'MainApp'。

MainApp 不包含在 Game.h 中,但 Game.h 包含在 MainApp.h 中。

想法?

最佳答案

问题是您有一个循环引用 - 游戏包括 MainApp,而 MainApp 包括游戏。根据 DeadMG 的示例,您需要“前向声明”。

参见 here .

关于C++ - 如何调用创建者类/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3422854/

相关文章:

c++ - 最小划分对象 vector (C++)

c++ - 保留子类的中央列表,但避免静态实例

php - 如何处理带有数组的对象以访问特定数据?

c++ - 如何检测错误写入

c++ - 创建自定义 tcl channel 驱动程序时出现段错误

javascript - 不知何故,我的类无法定义一些变量

java - 任何不良使用界面的例子?

c++ - C/C++ 的多线程内存分配器

memory - K8S容器是否使用主机操作系统的文件缓存

c++ - 当 UBSAN (-fsanitize=undefined) 发现未定义行为时触发测试失败