Class 成员未声明,即使我将 class 声明放在主循环之上

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

我正在自学如何在 C++ 中使用 类,当我这样做时 运行 遇到了一个问题:

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

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

error "slotOne" was not declared in this scope.

当我编译的时候。我正在使用 Code::Blocks,并在 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() 函数内,您正试图在 main 函数中访问变量 slotOne,而您没有名为 slotOne 的变量在其范围内声明。

您的代码同样有多个错误。库存函数的书面类型是字符串,但您正在尝试 return 一个 int 值,而不是您的库存函数应该 return int 如下

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

或者,如果您想要 return 字符串值

,则应将 return 值转换为字符串