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

标签 c++ class object parameters

所以,我正试图在我的 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/

相关文章:

c++ - cmake 链接 libboost_python-py32.so 而不是 libboost_python.so

c++ - 重新制定以前的状态 3 查询

c++ - 为什么必须在何处以及为什么要放置"template"和"typename"关键字?

ios - 创建一个由变量标识的类

php - OOP PHP 新手,需要对第一个 Geo RSS 类进行评论

php - PHP 中的对象重载有什么优势?

c++ - 无法调试 C++ eclipse makefile 项目

python - 从单独的文件导入类

c++ - 将对象添加到 vector

C# 试图使标签(对象)从表单的一侧反弹到另一侧