class A{
A(int a = 5){
DoSomething();
A();
}
A(){...}
}
Run Code Online (Sandbox Code Playgroud)
第一个构造函数可以调用第二个构造函数吗?
Ale*_*x B 16
不是之前C++0x,没有.
但是,出于学术兴趣,我想出了一个非常可怕的方法*使用贴片操作员"new"来做这件事(有人想指出这是多么便携?)
#include <new>
#include <iostream>
class A
{
public:
A(int i, int j)
: i_(i), j_(j) { }
A(int i)
{ new (this) A(i, 13); }
int i_,j_;
};
int
main() {
A a1(10,11), a2(10);
std::cout
<< a1.i_ << ", "
<< a1.j_ << std::endl
<< a2.i_ << ", "
<< a2.j_ << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
*不,不,我不在生产代码中写这个.
小智 6
答案实际上是"是",但正如其他人所建议的那样,它并不能满足您的需求.您当然可以隐式或显式地使用基类的构造函数:
struct B {
B() {}
B( int x ) {}
};
struct A : public B {
A() {} // calls B() implicitly
A( int a, int b ) : B( b ) {} // calls B(int) explicitly
};
Run Code Online (Sandbox Code Playgroud)