Sam*_*sey 4 c++ class-constructors
在C++中,我试图模仿Java如何处理对它的构造函数的调用.在我的Java代码中,如果我有两个不同的构造函数并希望有一个调用另一个,我只需使用this关键字.例:
public Constructor1(String s1, String s2)
{
//fun stuff here
}
public Constructor2(String s1)
{
this("Testing", s1);
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,通过使用Constructor2实例化一个对象(传入单个字符串),它将只调用Constructor1.这在Java中很有用,但我怎样才能在C++中获得类似的功能?当我使用this关键词时,它会抱怨并告诉我'this' cannot be used as a function.
这在具有构造函数委托的C++ 11中是可能的:
class Foo {
public:
Foo(std::string s1, std::string s2) {
//fun stuff here
}
Foo(std::string s1) : Foo("Testing", s1) {}
};
Run Code Online (Sandbox Code Playgroud)
您可以init为此类作业编写私有成员函数,如下所示:
struct A
{
A(const string & s1,const string & s2)
{
init(s1,s2);
}
A(const string & s)
{
init("Testing", s);
}
private:
void init(const string & s1,const string & s2)
{
//do the initialization
}
};
Run Code Online (Sandbox Code Playgroud)