创建类实例变量时出现问题
Trouble with creating class instance variables
我正在编写一个小程序来为开始的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";
}
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++理解计算字符变量的问题
- 在通知提升间处理条件变量时未按住锁会导致问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 将十六进制值设置为用于填充的字符变量时出现问题
- 初学者问题:如何访问此变量?
- 关于仅正确使用二传手和变量的问题
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 在 for 循环中更新两个变量时遇到问题C++
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题
- 模板类编译问题与 typedef 变量
- 简单的问题 - 如何从单独的"结构"内的'class'访问变量?
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 初学者问题:C++指针/地址 - 和变量之后不是以前?
- 关于读取有效 c++ 第 4 项(将非局部静态变量替换为局部静态变量)的问题
- 我有几个关于参考变量的问题
- 面临在 if 语句之外打印变量数据的问题 完成使用 Qt 编程
- OpenCV C++ Mat 类行和列 - 它们是成员变量(和相关问题)吗?
- 指向动态内存中结构中的变量时出现问题