可能重复:
Most vexing parse: why doesn't A a(()); work?
Difference between creating object with () or without
有这样的代码:
class MojaKlasa{
public:
MojaKlasa(){}
MojaKlasa(int i){}
void fun(){}
};
int main()
{
MojaKlasa a;
a.fun();
MojaKlasa b(1);
b.fun();
MojaKlasa c(); // initialize with default constructor
//c.fun(); error: request for member ‘fun’ in ‘c’, which is of non-class type ‘MojaKlasa()’
return 0;
}
答案 0 :(得分:4)
MojaKlasa c();
这声明了一个名为c
的函数返回MojaKlasa
,它不是一个对象声明。如果要声明本地对象,则需要省略括号。它只是一个语言规则,编译器必须将此表单解释为函数声明。
MojaKlasa c;
答案 1 :(得分:2)
MojaKlasa c();
定义了一个返回MojaKlasa对象的函数。
MojaKlasa c;
定义MojaKlasa类型的对象c。