将此对象传递到初始化列表 [英] Pass 'this' object to an initialization list

查看:175
本文介绍了将此对象传递到初始化列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将问题减少到以下示例代码:

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) {}


$ b b

不更改或添加公共成员,如何创建训练器的构造函数,以便在初始化列表中创建myPokemon时,myTrainer指向正在创建的训练器?

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?

这是我试过的:

trainer::trainer() : myPokemon(this) {}

但当然this不是正确的类型。我不能改变Charizard构造函数采用什么(它是一个公共成员),所以我不知道该怎么做。任何想法?

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.

推荐答案

如果你需要一个实例对象而不是指针,请尝试:

If you need an instance object instead of a pointer, try:

trainer::trainer() : myPokemon(*this) {}

Charizard 在其构造函数中调用 tMyTrainer 上的任何方法,因为您的新 trainer 对象尚未完全构建。

Be careful if Charizard tries to call any methods on tMyTrainer in its constructor, because your new trainer object has not yet been fully constructed at that time.

这篇关于将此对象传递到初始化列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆