开发者

Pass 'this' object to an initialization list

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.


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

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

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.


A reference type is expected - just use *this instead of this.

A lot of compilers will warn about this anyway: myPokemon will be constructed before trainer is done, so it gets a reference to a non-constructed trainer. Be careful not to call any methods on it (or use its data) since it leads to undefined behavior!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜