C++11: Yes!
(C ++ 11:是的!)
C++11 and onwards has this same feature (called delegating constructors ).
(C ++ 11及更高版本具有相同的功能(称为委托构造器 )。)
The syntax is slightly different from C#:
(语法与C#略有不同:)
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
C++03: No
(C ++ 03:否)
Unfortunately, there's no way to do this in C++03, but there are two ways of simulating this:
(不幸的是,在C ++ 03中没有做到这一点的方法,但是有两种模拟方法:)
You can combine two (or more) constructors via default parameters:
(您可以通过默认参数组合两个(或多个)构造函数:)
class Foo { public: Foo(char x, int y=0); // combines two constructors (char) and (char, int) // ... };
Use an init method to share common code:
(使用init方法共享通用代码:)
class Foo { public: Foo(char x); Foo(char x, int y); // ... private: void init(char x, int y); }; Foo::Foo(char x) { init(x, int(x) + 7); // ... } Foo::Foo(char x, int y) { init(x, y); // ... } void Foo::init(char x, int y) { // ... }
See the C++FAQ entry for reference.
(请参阅C ++ FAQ条目以供参考。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…