我对构造函数链接的理解是,当一个类中有多个构造函数(重载构造函数)时,如果其中一个试图调用另一个构造函数,那么 这个过程称为 CONSTRUCTOR CHAINING ,在 C++ 中不受支持。 最近在看网上资料的时候偶然发现了这一段……是这样的……
You may find yourself in the situation where you want to write a member function to re-initialize a class back to default values. Because you probably already have a constructor that does this, you may be tempted to try to call the constructor from your member function. As mentioned, chaining constructor calls are illegal in C++. You could copy the code from the constructor in your function, which would work, but lead to duplicate code. The best solution in this case is to move the code from the constructor to your new function, and have the constructor call your function to do the work of initializing the data.
调用构造函数的成员函数是否也属于构造函数链? 请用 C++ 阐明这个主题。
最佳答案
C++11 允许构造函数链接(部分)。此功能称为“delegating constructors”。因此,在 C++11 中,您可以执行以下操作
class Foo
{
public:
Foo(int a) : Foo() { _a = a; }
Foo(char* b) : Foo() { _b = b; }
Foo() { _c = 1.5; }
private:
int _a = 0;
char* _b = nullptr;
double _c;
};
但是,有一个严格的限制,即不允许调用另一个构造函数的构造函数来初始化任何其他成员。因此,您不能使用委托(delegate)构造函数执行以下操作:
class Foo
{
public:
Foo(int a) : Foo(), _a(a) { }
Foo(char* b) : Foo(), _b(b) { }
Foo() { _c = 1.5; }
private:
int _a = 0;
char* _b = nullptr;
double _c;
};
MSVC++2013 给出后一个代码示例的编译错误“C3511:对委托(delegate)构造函数的调用应是唯一的成员初始化程序”。
关于c++ - C++中的构造函数链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7349183/