I_don't_get_it
I_don't_get_it

Reputation: 3

Trying to pass a string as an argument for a class but it is being recognized as an array of chars instead in C++

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.

Upvotes: 0

Views: 153

Answers (2)

Rptx
Rptx

Reputation: 1189

You are asking for a reference to non-const int& in the constructor and providing an int literal. The error is telling you that there is no constructor taking an int as an argument. Passing the int by value should fix it. Also, A string literal (string between quotes) in C++, is a null terminated char array, not a std::string, although it can be used to construct one, and it's not causing the error in this case.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385104

The problem is not the string. The const char[7] would be successfully used to construct the temporary std::strings.

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 ints by value, as it does not need to modify the originals and ints are small:

Warrior(const string& input_name, int input_strength)
//                                ^^^
   : name(input_name)
   , strength(input_strength)
{}

Upvotes: 5

Related Questions