In C++, initialize a class member with #39;this#39; pointer during construction(在 C++ 中,在构造期间使用“this指针初始化类成员)
问题描述
我想创建一个以某种父子关系关联到另一个类的类.为此,子"类需要对其父类的引用.
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 的构造函数的实例化列表,因为那里不允许 this 引用.除了添加另一个方法 setParent(T*) (我不太喜欢它,因为这意味着我必须让 TEvent<> 实例无效state), 有没有办法做到这一点?
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"指针初始化类成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中,在构造期间使用“this"指针初始化类成员
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
