问题描述
作为开发人员,我习惯于运行构造函数:
class Test {
public Test(){
DoSomething ();
}
public Test(int count):this(){
DoSomethingWithCount(count);
}
public Test(int count,string name):this(count){
DoSomethingWithName(name);
}
}
在C ++中有办法吗? / p>
我尝试调用类名称并使用'this'关键字,但都失败了。
是!
C ++ 11及以上版本具有相同的功能(称为)。
语法与C#略有不同:
class Foo {
public:
Foo(char x,int y){}
Foo(int y):Foo('a',y){}
}
不幸的是没有办法在C ++ 03中做到这一点,但有两种方法来模拟:
1)您可以通过默认参数组合两个(或多个)构造函数:
class Foo {
public:
Foo(char x,int y = 0); //合并两个构造函数(char)和(char,int)
...
};
2)使用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)
{
...
}
请参阅以供参考。
As a C# developer I'm used to run through constructors:
class Test {
public Test() {
DoSomething();
}
public Test(int count) : this() {
DoSomethingWithCount(count);
}
public Test(int count, string name) : this(count) {
DoSomethingWithName(name);
}
}
Is there a way to do this in C++?
I tried calling the Class name and using the 'this' keyword, but both fails.
Yes!
C++11 and onwards has this same feature (called delegating constructors).
The syntax is slightly different from C#:
class Foo {
public:
Foo(char x, int y) {}
Foo(int y) : Foo('a', y) {}
};
Unfortunately there's no way to do this in C++03, but there are two ways of simulating this:
1) 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)
...
};
2) Use an init method to share common code
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 this link for reference.
这篇关于从C ++中的构造函数调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!