Guidance with header and main template - seek best practice please
I'm new to C++ and was needing some help in terms of using the best coding practices. Basically I have creat开发者_Python百科ed my header file (character.h) with the following data:
using namespace std;
class character
{
//available to all
public:
character();
~character(){};
int getHP(){return hp;};
int damage(int _damage);
int levelUp(int _xp);
void setHP(int _hp){hp = _hp;};
string getName(){return name;};
protected:
int hp;
string name;
};
class player:public character
{
public:
player();
~player(){};
protected:
string name;
int lvl;
int xp;
};
class enemy:public character
{
public:
enemy(string _name, int _hp);
~enemy(){};
protected:
string name;
int lvl;
int xp;
};
I was trying to generate the main file (main.cpp) from this data
#include "character.h"
player::player()
{
cout << "\t\t\nPlease enter your name: \n\t\t";
cin >> name;
};
int main()
{
//some code
return 0;
}
But I keep getting errors
"undefined reference to `character::character()"
Can someone please help me, why am I getting this error and also is this approach the best practice for the layout of this design?
You need to define the constructor(s) for character in your code file:
character::character():
hp(10),
name("default")
{
}
character::character (std::string name): hp(10) [...]
character::character (int hp): name("Default") [...]
character::character (std::string name, int hp) [...]
This makes sure that all your instance variables are defined.
Since you define a destructor, you must obey the rule of three and define a copy constructor and assignment operator as well.
On a side note, you should use a convention to name your class/instance variables: myName
, _name
, or name_
are quiet common. Using cppcheck may save you some time/hassle as well.
What you need to do is create the definition for your default constructors character::character()
and player::player()
. While default constructors take no arguments, you still need need to provide a definition for them. If they do absolutely nothing, not even member initialization, then you could simply do what you did for your destructors: character() { }
and player() { }
.
However, you could (and you probably should), initialize the data members in the constructors, using initializer list syntax. For example, for the character class, it would be:
character() : hp(100), name("Mario") { }
Note that you don't need the semicolon after }
. Or you could NOT use initializer lists and have:
character() {
hp = 100;
name = "Mario";
}
精彩评论