"this"不能用作函数
"this" Cannot Be Used As A Function
在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){}
效率不高,但和你想要的差不多。然而,我不建议这个选项,因为我上面提到的选项更好(就效率而言)。我只是想展示一种不同的方法。
相关文章:
- 递归模板化函数不能分配给具有常量限定类型"const tt &"的变量"state"
- 为什么虚函数不能是静态的和全局的?
- 为什么继承的受保护构造函数不能公开?
- C++为什么类成员函数不能重新声明,但普通函数可以
- 为什么在C++中使用关系运算符创建的模板函数不能对字符串正常工作?
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 为什么模板函数不能作为模板模板参数传递?
- 为什么 free 函数不能在 C 数组上运行,而 std::begin 在某些情况下可以在 C++14 中运行?
- 构造函数不能用于启发性化
- C 错误 - 函数不能超载
- 有没有办法使成员函数不能从构造函数调用
- 为什么模板函数不能是模板类的友元模板函数
- "Framework::Graphics::Material"的默认构造函数不能被引用 - 它是一个已删除的函数
- lower_bound()函数不能在调试模式下编译
- 为什么函数不能正确强制转换指针(从基类到派生类)
- 显式默认函数不能声明为 constexpr,因为隐式声明不是 constexpr
- 琐碎的默认构造函数不能是 constexpr?
- 函数不能嵌套,那么如何在C++中执行此操作
- 错误:成员函数不能在其类之外声明
- 错误-仅返回类型不同的函数不能重载.c++