创建类实例变量时出现问题

Trouble with creating class instance variables

本文关键字:问题 变量 实例 创建      更新时间:2023-10-16

我正在编写一个小程序来为开始的c ++课程生成一个字符。

我在库存部分遇到问题。

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

'return' : 无法从 'std::string'

转换为 '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;

更新

你来说,最好还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";
}