通过“这个”初始化列表的对象
我已将问题简化为以下示例代码:
class Charizard { //truck
trainer &myTrainer;
public:
Charizard(trainer &tMyTrainer);
};
class trainer {
Charizard myPokemon;
public:
trainer();
};
Charizard::Charizard(trainer &tMyTrainer) : myTrainer(tMyTrainer) {}
在不更改或添加公共成员的情况下,如何为训练器创建构造函数,以便在初始化列表中创建 myPokemon 时,“myTrainer”指向正在运行的训练器创建?
这是我尝试过的:
trainer::trainer() : myPokemon(this) {}
但当然“this”不是正确的类型。我无法更改 Charizard 构造函数所接受的内容(它是公共成员),所以我不知道该怎么做。有什么想法吗?
注意:标题可能需要一些修改。
I've reduced the problem down to the following sample code:
class Charizard { //truck
trainer &myTrainer;
public:
Charizard(trainer &tMyTrainer);
};
class trainer {
Charizard myPokemon;
public:
trainer();
};
Charizard::Charizard(trainer &tMyTrainer) : myTrainer(tMyTrainer) {}
Without changing or adding public members, how can I create the constructor for trainer, such that when myPokemon is created in the initialization list, the "myTrainer" points back to the trainer being created?
Here is what I tried:
trainer::trainer() : myPokemon(this) {}
But of course "this" is not the correct type. I cannot change what the Charizard constructor takes in (it's a public member), so I'm not sure what to do. Any ideas?
Note: Title might need some work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要实例对象而不是指针,请尝试:
如果
Charizard
尝试在其构造函数中调用tMyTrainer
上的任何方法,请小心,因为您的新trainer< /code> 对象当时尚未完全构建。
If you need an instance object instead of a pointer, try:
Be careful if
Charizard
tries to call any methods ontMyTrainer
in its constructor, because your newtrainer
object has not yet been fully constructed at that time.需要引用类型 - 只需使用
*this
而不是this
。无论如何,许多编译器都会对此发出警告:
myPokemon
将在trainer
完成之前构建,因此它会获得对非构造的trainer
的引用>。小心不要调用它的任何方法(或使用它的数据),因为它会导致未定义的行为!A reference type is expected - just use
*this
instead ofthis
.A lot of compilers will warn about this anyway:
myPokemon
will be constructed beforetrainer
is done, so it gets a reference to a non-constructedtrainer
. Be careful not to call any methods on it (or use its data) since it leads to undefined behavior!