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

1k views Asked by At

I have a block of code from my project to build a c++ roguelike with ncurses. I am trying to make it so that the player can hold two weapons. i have created a weaponItem class and two objects, but the compiler still throws a 'does not name a type' error.

Code:

weaponItem weapon1;
weaponItem weapon2;

weapon1.setType(DMW_DAGGER);
weapon2.setType(DMW_SBOW);

weapon1.setPrefix(DMWP_AVERAGE);
weapon2.setPrefix(DMWP_RUSTY);

Compiler Error:

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); 
  ^

Is there something wrong with my class or object declaration?

1

There are 1 answers

1
R Sahu On BEST ANSWER

I think you are misunderstanding the error message and some of the comments.

Say you have a class/struct.

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

You can define objects of type Foo outside function definitions.

// OK
Foo foo1;

However, you cannot call a member function of the class outside function definition by itself.

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

You can make function call inside a function definition in the file.

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

You can call a member function outside function definitions if you use its return value to initialize another variable.

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

// OK
Foo foo1;
int x = foo1.get();