我有一个有两个构造函数的类,一个不带参数,一个带一个参数。
使用带有一个参数的构造函数创建对象按预期工作。但是,如果我使用不带参数的构造函数创建对象,则会出现错误。
例如,如果我编译这段代码(使用 g++ 4.0.1)...
class Foo
{
public:
Foo() {};
Foo(int a) {};
void bar() {};
};
int main()
{
// this works...
Foo foo1(1);
foo1.bar();
// this does not...
Foo foo2();
foo2.bar();
return 0;
}
...我收到以下错误:
nonclass.cpp: In function ‘int main(int, const char**)’:
nonclass.cpp:17: error: request for member ‘bar’ in ‘foo2’, which is of non-class type ‘Foo ()()’
为什么会这样,我该如何让它发挥作用?
最佳答案
Foo foo2();
改成
Foo foo2;
你得到错误是因为编译器认为
Foo foo2()
从函数声明开始,名称为“foo2”,返回类型为“Foo”。
但在这种情况下,如果我们更改为 Foo foo2
,编译器可能会显示错误 "call of overloaded 'Foo()' is ambiguous"
。
关于c++ - 错误 : request for member '..' in '..' which is of non-class type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/877523/