关于字符的C++初学者问题

Sam*_*hoo 2 c++

我只是在试图制作一个简单的井字游戏时,正在搞乱一些C++,而我遇到了一些问题.这是我的代码:

#include <iostream>
using namespace std;

class Square {
public:
    char getState() const;
    void setState(char);
    Square();
    ~Square();
private:
    char * pState;
};

class Board {
public:
    Board();
    ~Board();
    void printBoard() const;
    Square getSquare(short x, short y) const;
private:
    Square board[3][3];
};

int main() {
    Board board;
    board.getSquare(1,2).setState('1');
    board.printBoard();
    return 0;
}

Square::Square() {
    pState = new char;
    *pState = ' ';
}
Square::~Square() {
    delete pState;
}
char Square::getState() const {
    return *pState;
}
void Square::setState(char set) {
    *pState = set;
}

Board::~Board() {

}
Board::Board() {

}
void Board::printBoard() const {
    for (int x = 0; x < 3; x++) {
        cout << "|";
        for (int y = 0; y < 3; y++) {
            cout << board[x][y].getState();
        }
        cout << "|" << endl;
    }
}
Square Board::getSquare(short x, short y) const {
    return board[x][y];
}
Run Code Online (Sandbox Code Playgroud)

原谅我,如果它有明显的明显问题或者是愚蠢的写,这是我在C++中的第一个程序:p然而,问题是当我尝试将方形1,2设置为字符'1'时,它不会'打印出来作为1,它打印出一些我不认识的奇怪角色.

谁能告诉我为什么?:)

提前致谢.

Mat*_*ler 5

Board::getSquare方法返回该对象的副本Square.pState复制Square对象的变量指向与原始Square对象相同的字符.复制的Square对象被销毁时,会删除变量char指向的对象pState.这会使char对象中的Square对象无效Board.当您打印时,您正在打印无效char对象.

正如其他人所说,pState变量应该是一个char而不是一个char*.这将使您在解决问题方面向前迈出一步.您仍然需要处理返回Square对象的引用而不是对象的副本Square.