C++ 使用"this"作为参数?

C++ Use "this" as a parameter?

本文关键字:参数 this 使用 C++      更新时间:2023-10-16

所以,我试着在我的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;
    }
}

我甚至不确定这段代码是否正确,因为我现在创建它只是为了显示我想要做的。

所以,基本上,我想做的是在"屏幕"中创建一个"游戏"的引用,这样我就可以使用它的属性和方法(在这种情况下,屏幕宽度),即使"屏幕"在"游戏"中被实例化。我在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);
}

a)前向声明Game类

b)使Screen(Game *game)构造函数接受一个指针而不是一个对象,因为你正在传递这个指针。

参考以下示例

http://ideone.com/J8He9f