我正在编写一个小程序来为开始的c ++课程生成一个字符。
我在库存部分遇到问题。
我使用Visual Studio,当我尝试设置库存数组时,出现此错误:
'返回' :无法转换为' 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;
}
答案 0 :(得分:1)
以下功能出现问题:
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";
}