c++ - 错误 : request for member '..' in '..' which is of non-class type

标签 c++

我有一个有两个构造函数的类,一个不带参数,一个带一个参数。

使用带有一个参数的构造函数创建对象按预期工作。但是,如果我使用不带参数的构造函数创建对象,则会出现错误。

例如,如果我编译这段代码(使用 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/

相关文章:

c++ - 如何使用 OpenCV 将齐次点转换为非齐次点(C++ 中)

c++ - unique_ptr 的取消引用运算符在 Eclipse 中不起作用

c++ - 构建项目时 Unresolved external symbol 错误

c++ - 从 C++ std::vector 中删除元素

c++ - 使用 DebugActiveProcess 和 WaitForDebugEvent 似乎挂起

c++ - 通过 ref-qualifier 重载操作符以防止临时操作是否合理?

c++ - Unicode、字符指针和 wcslen

与基类同名的 C++ 类成员

c++ - 有没有办法用循环删除两个给定值?

c++ - 如何从 elf 文件的节标题中提取所有字段?