<分区>
我正在用 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++ 新手,请尽可能具体。