编译器给出错误:声明后立即"Does not name a type"

Compiler gives error: "Does not name a type" immediately after declared

本文关键字:Does not name type 出错 错误 声明 编译器      更新时间:2023-10-16

我的项目中有一块代码,用于用ncurses构建c++roguelike。我正在努力让玩家能够持有两件武器。我已经创建了一个weaponItem类和两个对象,但编译器仍然抛出"不命名类型"错误。

代码:

weaponItem weapon1;
weaponItem weapon2;
weapon1.setType(DMW_DAGGER);
weapon2.setType(DMW_SBOW);
weapon1.setPrefix(DMWP_AVERAGE);
weapon2.setPrefix(DMWP_RUSTY);

编译器错误:

In file included from main.cpp:2:0:
hero.h:17:2: error: ‘weapon1’ does not name a type
  weapon1.setType(DMW_DAGGER);
  ^
hero.h:18:2: error: ‘weapon2’ does not name a type
  weapon2.setType(DMW_SBOW);
  ^
hero.h:20:2: error: ‘weapon1’ does not name a type
  weapon1.setPrefix(DMWP_AVERAGE);
  ^
hero.h:21:2: error: ‘weapon2’ does not name a type
  weapon2.setPrefix(DMWP_RUSTY); 
  ^

我的类或对象声明有问题吗?

我认为您误解了错误消息和一些注释。

假设你有一个类/结构。

struct Foo
{
   Foo() : a(0) {}
   void set(int in) { a = 10; }
   int a;
};

可以在函数定义之外定义Foo类型的对象。

// OK
Foo foo1;

但是,不能在函数定义之外单独调用类的成员函数。

// Not OK in namespace scope or global scope.
foo1.set(20);

您可以在文件中的函数定义内进行函数调用。

// OK.
void testFoo()
{
   foo1.set(20);
}

如果使用成员函数的返回值初始化另一个变量,则可以在函数定义之外调用该成员函数。

struct Foo
{
   Foo() : a(0) {}
   void set(int in) { a = 10; }
   int get() { return a; }
   int a;
};
// OK
Foo foo1;
int x = foo1.get();