SkyeBoniwell
SkyeBoniwell

Reputation: 7092

Trouble with creating class instance variables

I'm writing a little program to generate a character for a beginning c++ course.

I'm having trouble with the inventory part.

I'm using Visual Studio and when I try to set the inventory array, I get this error:

'return' : cannot convert from 'std::string' to 'std::string *'

Googling didn't really turn up anything that worked.

Could someone take a look at the code and clue me in as to why it's failing?

Thanks

using namespace std;

int generateXp(int);


class Character {
private:

int xp = 0;
static const string inv[4];

public:

void setXp(int xp){
    this->xp = xp;
}

int getXp() {
    return this->xp;
}

string *getInv();

string* Character::getInv() {
string inv = { "shield", "chainmail", "helmet" };
return inv;
}

int main()
{
srand(time(NULL));

Character * Gandalf = new Character;
cout << "Gandalf has " << Gandalf->getXp() << " experience points.\n";
Gandalf->setXp(generateXp(100));
cout << "Gandalf now has " << Gandalf->getXp() << " experience points.\n";
cout << "Inventory " << Gandalf->getInv() << "\n";
}

int generateXp(int base)
{
int randomNumber = 0;

randomNumber = (rand() % 5000) + 1;

return randomNumber;
}

Upvotes: 0

Views: 38

Answers (1)

R Sahu
R Sahu

Reputation: 206577

Problem in the following function:

string* Character::getInv()
// ^^^^ The return type is std::string*
{
   string inv = { "shield", "chainmail", "helmet" };
   return inv;
   // And you are returning a std::string
}

Instead of:

string inv = { "shield", "chainmail", "helmet" };
return inv;

You probably meant:

static string inv[] = { "shield", "chainmail", "helmet" };
return inv;

Update

It will be better for you return a std::vector. Then you can access the contents of a std::vector more easily. You don't have to make assumptions about the size of the array.

std::vector<std::string> const& Character::getInv()
{
   static std::vector<std::string> inv = { "shield", "chainmail", "helmet" };
   return inv;
}

Change the usage:

std::vector<std::string> const& inv = Gandalf->getInv();
cout << "Inventory: \n";
for (auto const& item : inv )
{
   cout << item << "\n";
}

Upvotes: 1

Related Questions