Jus*_*ica 4 c++ constructor c++11
我想知道关于派生类构造函数的委派。当您还必须调用父类的构造函数时,委托构造函数的正确方法是什么?我知道您不能在同一初始化列表中同时包含委托和成员初始化,但是我不知道调用父类的构造函数是否具有相同的限制。
// Option 1: Call parent class constructor, then delegate:
class Foo {
public:
Foo(int);
};
class Bar : public Foo {
public:
Bar(int, float) : Foo(int), Bar(int, float, 'c');
Bar(int, float, char);
};
// Option 2: Delegate, then call parent class constructor:
class Foo {
public:
Foo(int);
};
class Bar : public Foo {
public:
Bar(int, float) : Bar(int, float, 'c'), Foo(int);
Bar(int, float, char);
};
// Option 3: Primary constructor calls parent class constructor:
class Foo {
public:
Foo(int);
};
class Bar : public Foo {
public:
Bar(int, float) : Bar(int, float, 'c');
Bar(int, float, char) : Foo(int);
};
Run Code Online (Sandbox Code Playgroud)
我认为它是#1或#3(最有可能是#3),但是我不确定。我知道这不是组合,因为那样会调用Foo()两次。我不认为它是第二名,但我列出它只是为了涵盖所有可能性。
我知道C ++中的委派也有一个怪异的属性,因为该类的任何构造函数完成执行后,就立即认为该类已被构造,即使您将调用委派给了另一个调用也没有完成了实际上被[i]称为[/ i]的那个。在这种情况下,我认为这不会产生任何影响,但是值得一提。
我搜索了该网站并在Google上进行了搜索,但找不到确切答案;我能找到的最接近的地方是,在MSDN上没有在同一init列表中进行委派和初始化。目前,我无法通过完全兼容C ++ 11的编译器运行一些测试代码,因此我不能只是做实验。帮助将不胜感激。
提前致谢。
这是唯一有效的选项:
class Bar : public Foo {
public:
Bar(int, float) : Bar(int, float, 'c') {}
Bar(int, float, char) : Foo(int) {}
};
Run Code Online (Sandbox Code Playgroud)
如果您的构造函数进行委托,则其 mem-initializer-list 允许仅包含单个委托构造函数调用。