所以,我正试图在我的 C++ 程序中重现我在 Java 中学到的一件事,但我无法做到这一点!
这是我想做的一个例子:
class Game{
public:
int screenWidth, screenHeight;
Screen* titleScreen;
void createScreen(){
titleScreen = new Screen(this);
}
}
class Screen{
public:
Game* game;
Rect quad1;
Screen(Game* game){
this->game = game;
quad1.x = game->screenWidth/2;
}
}
我什至不确定这段代码是否正确,因为我现在创建它只是为了展示我想做什么。
所以,基本上,我想做的是在“Screen”中为“Game”创建一个引用,这样我就可以使用它的属性和方法(在本例中为屏幕宽度),即使“Screen”正在被实例化在“游戏”里面。我在 Java 中做了类似的事情并且它工作得很好,但是对于 C++ 我得到了很多错误,我什至不知道如何解释它们......我尝试使用指针作为参数而不是使用“this”我试过使用“&this”但它们都不起作用,我得到了几乎相同的错误...
那么,我做错了什么?我怎样才能使这项工作?这在 C++ 中甚至可能吗?
最佳答案
使用前向声明并在定义它需要的东西之后定义函数。
class Screen; // Forward declaration
class Game{
public:
int screenWidth, screenHeight;
Screen * titleScreen;
void createScreen();
}
class Screen{
public:
Game* game;
Rect quad1;
Screen(Game *game){
this->game = game;
quad1.x = game->screenWidth/2;
}
}
// Out-of-line definition.
// This should be declared "inline" if it's in a header file.
void Game::createScreen(){
titleScreen = new Screen(this);
}
关于C++ 使用 "this"作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24277408/