I am having problems initializing Warrior Objects in my main function
The code for my Warrior Class is below
class Warrior{
public:
Warrior(const string& input_name, int& input_strength) :name(input_name), strength(input_strength) {};
string getname()const{
return name;
};
int getstrength(){
return strength;
};
void change_strength(int damg_taken){
strength -= damg_taken;
};
private:
string name;
int strength;
};
This is part of the code for the main function
Warrior cheetah("Tarzan", 10);
Warrior wizard("Merlin", 15);
Warrior theGovernator("Conan", 12);
Warrior nimoy("Spock", 15);
Warrior lawless("Xena", 20);
Warrior mrGreen("Hulk", 8);
Warrior dylan("Hercules", 3);
All of the Warrior initializations in the main function cause a error that is something like this:
Error:no instance of constructor "Warrior::Warrior" matches the argument list argument types are:(const char[7],int)
I read somewhere that strings in C++ are actually arrays of chars and that is why the warrior initialization are not working but I don't know how to change the constructor to make the program work. Also I am not allowed to change the main function because it was provided by the instructor.
The problem is not the string. The const char[7]
would be successfully used to construct the temporary std::string
s.
The problem is you are trying to bind int
literals to references-to-non-const
; you cannot do that. Accepting const int&
into your constructor would fix your program.
However, I recommend changing your constructor to take its int
s by value, as it does not need to modify the originals and int
s are small:
Warrior(const string& input_name, int input_strength)
// ^^^
: name(input_name)
, strength(input_strength)
{}