在c++中,我试图模仿Java如何处理对其构造函数的调用。在我的Java代码中,如果我有两个不同的构造函数,并且希望其中一个调用另一个,我只需使用this
关键字。例子:
public Constructor1(String s1, String s2)
{
//fun stuff here
}
public Constructor2(String s1)
{
this("Testing", s1);
}
在这段代码中,通过用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) {}
};
可以编写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
}
};
这在c++中是无法实现的。解决方法是创建一个带有默认参数的构造函数。
。
class Foo {
public:
Foo(char x, int y=0); // this line combines the two constructors
...
};
或者,您可以使用包含公共代码的单独方法。然后在两个构造函数中,使用适当的参数调用helper方法。
你要找的是构造函数重载
另一种说法:
Foo(int a){ *this = Foo(a,a); }
Foo(int a, int b): _a(a), _b(b){}
效率不高,但和你想要的差不多。然而,我不建议这个选项,因为我上面提到的选项更好(就效率而言)。我只是想展示一种不同的方法。