可以在c ++中构造函数调用另一个构造函数?
问题描述:
class A{
A(int a = 5){
DoSomething();
A();
}
A(){...}
}
第一个构造函数是否可以调用第二个构造函数?
Can the first constructor call the second one?
答
不要 before C ++ 11 。
将公共功能提取到单独的函数中。我通常命名这个函数 construct()
Extract the common functionality into a separate function instead. I usually name this function construct().
所谓的第二个调用将编译,但在C ++中有不同的含义:它会构造一个新的对象,一个临时的,然后立即在语句结束时删除。所以,不是。
The "so-called" second call would compile, but has a different meaning in C++: it would construct a new object, a temporary, which will then be instantly deleted at the end of the statement. So, no.
但是,析构函数可以毫无问题地调用。
A destructor, however, can be called without a problem.