本文介绍了不能声明具有一个参数的匿名对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有这个代码:
class SomeClass
{
public:
SomeClass(){}
SomeClass(SomeClass& b){}
SomeClass(SomeClass&b, SomeClass& c){}
};
int main()
{
SomeClass a;
SomeClass(); // works all right
//SomeClass(a); error: redeclaration of ‘SomeClass a’
SomeClass(a, a); // works all right
return 0;
}
可以声明SomeClass的具有0和2个参数的匿名对象,只用一个参数声明。我假设写入
Anonymous object of SomeClass with 0 and 2 parameters can be declared, however it cannot be declared with only 1 argument. I assume that writing
SomeClass(a);
与
SomeClass a;
如何创建带有一个参数的匿名对象?
How to create anonymous object with one argument?
推荐答案
您可以在自己的语句中构建一个临时对象,例如:
You can construct a temporary object in a statement of its own with something like:
(SomeClass)a;
或
(SomeClass(a));
正如你所观察到的,需要使用括号来解决声明和表达式语句之间的歧义
As you've observed, the parentheses are needed to resolve the ambiguity between a declaration and an expression statement.
这篇关于不能声明具有一个参数的匿名对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!