class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
class SomeType
{
int number;
public:
SomeType(int newNumber) : number(newNumber) {}
SomeType() : SomeType(42) {}
};
我相信您可以从构造函数中调用构造函数。它将编译并运行。我最近看到有人这样做,并且可以在 Windows 和 Linux 上运行。
它只是不做你想要的。内部构造函数将构造一个临时本地对象,一旦外部构造函数返回,该本地对象将被删除。它们也必须是不同的构造函数,否则您将创建递归调用。
class A { /* ... */ };
class B : public A
{
B() : A()
{
// ...
}
};
class Foo {
int d;
public:
Foo (int i) : d(i) {}
Foo () : Foo(42) {} //New to C++11
};
class Foo {
int d = 5;
public:
Foo (int i) : d(i) {}
};
class Foo() {
Foo() { /* default constructor deliciousness */ }
Foo(Bar myParam) {
new (this) Foo();
/* bar your param all night long */
}
};
class Foo() {
private:
std::vector<int> Stuff;
public:
Foo()
: Stuff(42)
{
/* default constructor deliciousness */
}
Foo(Bar myParam)
{
this->~Foo();
new (this) Foo();
/* bar your param all night long */
}
};
不,在 C ++ 中,您不能从构造函数调用构造函数。正如沃伦指出的,您可以做的是:
请注意,在第一种情况下,您不能通过从另一个构造函数调用另一个代码来减少代码重复。当然,您可以有一个单独的私有 / 受保护的方法来执行所有初始化,并让构造函数主要处理参数处理。
简而言之,您不能在 C ++ 11 之前。
C ++ 11 引入了委托构造函数 :
委托构造函数
如果类本身的名称在成员初始值设定项列表中显示为 class-or-identifier,则该列表必须仅由该一个成员初始值设定项组成;这样的构造函数称为委托构造函数,并且由初始化程序列表的唯一成员选择的构造函数是目标构造函数
在这种情况下,将通过重载决议选择目标构造函数并首先执行它,然后控件返回到委托构造函数并执行其主体。
委托构造函数不能是递归的。
class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int) };
请注意,委派构造函数是一个全有或全无的提议。如果一个构造函数委托给另一个构造函数,则不允许调用构造函数在其初始化列表中包含任何其他成员。如果您考虑一次初始化 const / reference 成员,并且仅一次初始化,则这很有意义。
class Vertex
{
private:
int x, y;
public:
Vertex(int xCoo, int yCoo): x(xCoo), y(yCoo) {}
Vertex()
{
this->Vertex::Vertex(-1, -1);
}
};
class Test_Base {
public Test_Base() {
DoSomething();
}
};
class Test : public Test_Base {
public Test() : Test_Base() {
}
public Test(int count) : Test_Base() {
DoSomethingWithCount(count);
}
};