创建 class 个实例变量时遇到问题

Trouble with creating class instance variables

我正在编写一个小程序来为初级 C++ 课程生成一个字符。

我在库存部分遇到了问题。

我正在使用 Visual Studio,当我尝试设置库存数组时,出现此错误:

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

谷歌搜索并没有真正找到任何有用的东西。

有人可以看一下代码并告诉我失败的原因吗?

谢谢

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;
}

以下函数有问题:

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

而不是:

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

你的意思可能是:

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

更新

对你来说会更好return一个std::vector。然后你可以更容易地访问 std::vector 的内容。您不必对数组的大小做出假设。

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

更改用法:

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