即使我将班级声明置于主循环之上,也没有宣布班级成员

Class members are not declared, even when I put the class declaration above the main loop

本文关键字:成员 布班级 循环 于主 声明      更新时间:2023-10-16

我正在教自己如何在C 中使用课程,当我这样做时,我会遇到一个问题:

cout << One.Player::inventory(slotOne);

我不确定为什么,但它告诉我:

错误在此范围中没有声明" slotone"。

我编译时。我正在使用Code ::块,并在Windows 10版本1709,构建12699.192上使用GNU/GCC编译器,并且以前从未遇到过此类问题。我做错了什么,我该如何解决?

#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <algorithm>
using namespace std;
std::string longsword = "Longsword: 1d8 slashing";
std::string shortsword = "Shortsword: 1d6 slashing";
std::string dagger = "Dagger: 1d4 slashing";
std::string falchion = "Falchion: 1d10 slashing";
std::string longbow = "Longbow: 1d8 piercing t Range: 110/330 yards";
class Player {
public:
    std::string inventory();
    int health();
    int hunger();
    int exhaustion();
};
int main() {
    srand(time(NULL));
    string playername;
    Player One;
    cout << "Welcome to -WIP-." << endl;
    cout << "What is your name? n";
    cin >> playername;
    cout << One.Player::inventory(slotOne);
    return 0;
}
int Player::health()
{
    int hp = 10;
    cout << "Current health is: " << hp << endl;
    return 0;
}
std::string Player::inventory() {
    std::string slotOne = longsword;
    std::string slotTwo = longbow;
    return 0;
}

从代码中我看到的slotone变量范围在player :: inventory((函数中,并且您正在尝试访问主函数中的变量slotone,而其中中没有一个在其范围内声明的名称slotone的变量。

再次,您的代码有多个错误。库存函数的书面类型是字符串,但您正在尝试返回int值,而是您的库存函数应该返回int,要么像

int Player::inventory()
{
    std::string slotOne = longsword;
    std::string slotTwo = longbow;
    return 0;
}

,或者如果要返回字符串值

,则应将返回值转换为字符串