C++:新手初始化列表问题
这里是新手。我正在查看公司代码。
看起来类 A 中没有成员变量,但在 A 的构造函数中它初始化了对象 B,即使类 A 不包含任何 B 类型的成员变量(或根本不包含任何成员变量!)。
我想我还不太明白,甚至无法提出问题……所以这是怎么回事!?我的直觉是,在尝试初始化变量之前,您需要一个变量。在没有对象的情况下如何可能(或者它有什么好处)初始化对象?
.h:
class A: public B
{
public:
A(bool r = true);
virtual ~A;
private:
}
.cpp:
A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
}
A::~A()
{
}
请帮忙。
谢谢, 吉布
Newbie here. I am looking at company code.
It appears that there are NO member variables in class A yet in A's constructor it initializes an object B even though class A does not contain any member variable of type B (or any member variable at all!).
I guess I don't understand it enough to even ask a question...so what's going on here!? My intuition is that you need a variable before you even try to initialize it. How is it possible (or what good does it do) to initialize an object without having the object?
.h:
class A: public B
{
public:
A(bool r = true);
virtual ~A;
private:
}
.cpp:
A::A(bool r) : B(r ? B::someEnumeration : B::anotherEnumeration)
{
}
A::~A()
{
}
Please help.
Thanks,
jbu
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
类
A
(公开)继承 来自类B
:唯一的方式使用参数初始化基类是通过初始化列表。
Class
A
(publicly) inherits from classB
:The only way to initialize a base class with parameters is through the initializer list.
这实际上是在 C++ 中调用基类的 ctor 的唯一方法,因为没有
super()
这样的东西。This is actually the only way to call the ctor of a base class in C++ as there is noch such thing as
super()
.A 是 B 的派生类型。或者 A 继承 B。
所以这是有效的...
其余代码只是在构造 A 时调用 B 的构造函数。
A is a derived type from B. Or A inherits B.
So this is valid...
The rest of your code is just calling B's constructor when A is constructed.
.cpp
.cpp
由于构造函数不能被继承,因此基类数据成员将通过在派生类构造函数中传递参数并借助初始化列表来初始化。
您还应该知道,在多态类的情况下,vptr 初始化到相应的虚拟表仅在构造函数中完成。
Since construtor cannot be inherited so base class data members are to be initialized by passying argument in derived class constructor and with the help of initialization list.
You should also know that in case of polymorphic class initialization of vptr to respective virtual table is done only in constructor.