在标头中声明时,变量未在范围中声明

时间:2018-01-25 00:54:12

标签: c++

我正在用C ++制作Tic Tac Toe游戏。我在Header和cpp中声明了这个变量(slot1)我尝试使用这个变量,但它说“error:'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 ++的新手,请尽可能具体。

1 个答案:

答案 0 :(得分:1)

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

char s1ot1 = '1';

更改为

char slot1 = '1';