在C ++中,在构造期间使用“this”指针初始化类成员 [英] In C++, initialize a class member with 'this' pointer during construction
问题描述
我想创建一个类,它与某种父子关系中的另一个类相关联。为此,child类需要引用它的父类。
I'd like to create a class that is associated to another class in some sort of parent-child relationship. For this the "child" class needs a reference to it's parent.
例如:
template <typename T>
class TEvent {
private: T* Owner;
public: TEvent(T* parent) : Owner(parent) {}
};
class Foo {
private: TEvent<Foo> Froozle; // see below
};
现在问题是我不能初始化 Froozle
实例,也不使用Foo的构造函数的instanciation列表,因为 this
引用不允许。除了添加另一个方法 setParent(T *)
(我不喜欢太多,因为它意味着我必须离开 TEvent< ;
Now the problem is that I can't initialize the Froozle
instance directly, nor using the instanciation list of Foo's constructor, because this
references are not allowed there. Apart from adding another method setParent(T*)
(which I don't like too much because it means that I have to leave the TEvent<>
instance in an invalid state), is there a way to achieve this?
推荐答案
这是一个无效状态的实例确定在初始化列表中使用 this
,只要它不用于访问可能尚未初始化的任何成员。
It is OK to use this
in the initialization list, as long as it is not used to access any members that may not have been initialized yet.
这篇关于在C ++中,在构造期间使用“this”指针初始化类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!