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?
I think you are misunderstanding the error message and some of the comments.
Say you have a class/struct.
You can define objects of type
Foo
outside function definitions.However, you cannot call a member function of the class outside function definition by itself.
You can make function call inside a function definition in the file.
You can call a member function outside function definitions if you use its return value to initialize another variable.