C++ 使用"this"作为参数?
C++ Use "this" as a parameter?
所以,我试着在我的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相关文章:
- 了解'this'或其他参数是否为右值
- C++ Boost - 序列化错误 - 将"const B"作为"this"参数
- 成员函数的"this"参数具有"const"类型,但我的函数实际上不是"const"
- 整体模板参数。错误:在常量表达式中使用'this'
- 有没有办法绕过错误"因为'this'参数会丢弃限定符?
- 传递'const QVariant' 'this'参数会丢弃限定符 [-允许]
- C++错误:将"const umap_int {aka const std::unordered_map<int, int>}"作为"this"参数会丢弃限定符 [-permissive]
- 错误:将 x 作为 x 的参数传递'this'丢弃限定符
- C++ 不允许将'this'用作非类型模板参数
- const std::unordered_map<char, int>' 因为 'this' 参数会丢弃 lambda 中的限定符
- 为什么有必要将"this"指针作为"arg"参数传递给pthread_create
- 在模板类中使用"this"会导致参数初始化错误
- 错误:将“const sdf”作为“this”参数传递会丢弃限定符 [-fpermissive]
- 视觉C++:即使使用关键字,参数声明也会隐藏类成员"this"
- 错误:候选函数不可行:'this'参数具有类型 'const' 但方法未标记为 const
- 错误:将'xxx'作为'xxx'丢弃限定符的参数传递'this' [-允许]
- 用static_cast(*this)...初始化可变参数CRTP:<Base>合法吗?
- C++集合方法:函数'setCost'不可行:'this'参数的类型'const value_type'
- 如何理解C++隐式参数"this"
- C++:何时应该通过引用使用 PLUS 参数"this->"