c++ - 在标题中声明时未在范围内声明变量

标签 c++

<分区>

我正在用 C++ 制作 Tic Tac Toe 游戏。我在 header 和 cpp 中声明了这个变量 (slot1),我试图使用这个变量,但它显示“错误:'slot1' 未在此范围内声明”。

//main.cpp
#include <iostream>
#include <string>
#include "TicTacToe.h"

using namespace std;

TicTacToe gameOn;

int main()
{
    gameOn.startGame();
    return 0;
}





//TicTacToe.h
#ifndef TICTACTOE_H
#define TICTACTOE_H


class TicTacToe
{
    public:
        void startGame();
        void setupGame();

        //As you can see slot1 is clearly declared
        char s1ot1 = '1'; char slot2 = '2'; char slot3 = '3';
        char slot4 = '4'; char slot5 = '5'; char slot6 = '6';
        char slot7 = '7'; char slot8 = '8'; char slot9 = '9';

};

#endif // TICTACTOE_H





//TicTacToe.cpp
#include <iostream>
#include "TicTacToe.h"
#include <stdlib.h>
#include <string>

using namespace std;

string mode;

void TicTacToe::startGame()
{
    system("cls");
    cout << "This is a Tic Tac Toe game \n This game needs 2 players" << endl;
    while(true){
        cout << "Will you play? (Yes/No)" << endl;
        cin >> mode;
        if(mode == "Yes"){
            break;
        }else if(mode == "No"){
            cout << "Thank you for choosing this game..." << endl;
            exit(0);
            break;
        }else{
            cout << "Your input is invalid" << endl;
        }
    }
    setupGame();
}

void TicTacToe::setupGame(){
    cout << slot1 << " | " << slot2 << " | " << slot3 << endl; //slot1 variable "was not declared"
    cout << "----------------------" << endl;
    cout << slot4 << " | " << slot5 << " | " << slot6 << endl;
    cout << "----------------------" << endl;
    cout << slot7 << " | " << slot8 << " | " << slot9 << endl;
}

我改变了数据类型并运行良好,但问题是那个特定的变量,因为如果我完全删除它,其他字符被正常接受,当它们被写入与 slot1 完全相同时。我的代码有什么问题?

我是 C++ 新手,请尽可能具体。

最佳答案

您声明了 s1ot1 而不是 slot1(注意 1(“one”)而不是“l”):

char s1ot1 = '1';

改为

char slot1 = '1';

关于c++ - 在标题中声明时未在范围内声明变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48434025/

相关文章:

c++ - constexpr static std::array<const char *,5> 无法使用 MSVC2013 进行编译

c++ - 是否添加到 "char *"指针 UB,但它实际上并不指向 char 数组?

C++字符数组分配错误

c++ - 为什么我的析构函数被调用,我该如何修复它

android - Necessitas SDK for android app with Qt

c++ - 如何在 PhysX 中创建非碰撞刚体

c# - 你能喝一个 boost::optional<> 吗?

c++ - 添加更多代码会使代码无法编译

c++ - std::thread::id 是否有 "null"值?

C++ 疯狂 typedef : what is the point of allowing this syntax by the Standard?