1.棋子类
使用面向对象的方法不仅使得一些变量名正言顺,就是使变量有自己的归宿,而不是孤零零的躺在外面,用的什么也不知道是什么地方的,使用面向对象,可以明确知道这个是谁的属性,要从哪里得到它。
1.1.头文件
这里值得说明的是拷贝构造函数,不写的话会有问题。
我们要在处理棋子的时候添加棋子到储存棋子的数组里,涉及到拷贝构造,如果不写的话它会有错误,认为默认是被删除的,所以添加进去的棋子数据应该是不存在了,自己重写一个才行,注意是赋值运算符重载。
简简单单的写上这么一小个就好了。
#ifndef CHESS_H
#define CHESS_H
#include <QObject>
#include <QPoint>
class Chess : public QObject
{
Q_OBJECT
public:
explicit Chess(QObject *parent = nullptr);
Chess(const Chess& c);
void operator=(const Chess& c);
void setChessInfo(int x,int y,int color);
QString getChessInfo();
void setPoint(int x,int y);
QPoint getPoint();
void setX(int x);
int getX();
void setY(int y);
int getY();
void setColor(int color);
int getColor();
static int width;
static int height;
private:
int x;
int y;
int color;
signals:
};
#endif // CHESS_H
1.2.源文件
都是一些简简单单的函数,没有什么能够说明的。
#include "chess.h"
int Chess::width = 35;
int Chess::height = 35;
Chess::Chess(QObject *parent) : QObject(parent)
{
this->x = 0;
this->y = 0;
this->color = 0;
}
Chess::Chess(const Chess &c)
{
this->x = c.x;
this->y = c.y;
this->color = c.color;
}
void Chess::operator=(const Chess &c)
{
this->x = c.x;
this->y = c.y;
this->color = c.color;
}
void Chess::setChessInfo(int x, int y, int color)
{
this->x = x;
this->y = y;
this->color = color;
}
QString Chess::getChessInfo()
{
return QString::number(this->x)+QString::number(this->y)+QString::number(this->color);
}
void Chess::setPoint(int x, int y)
{
this->x = x;
this->y = y;
}
QPoint Chess::getPoint()
{
return QPoint(this->x,this->y);
}
void Chess::setX(int x)
{
this->x = x;
}
int Chess::getX()
{
return this->x;
}
void Chess::setY(int y)
{
this->y = y;
}
int Chess::getY()
{
return this->y;
}
void Chess::setColor(int color)
{
this->color = color;
}
int Chess::getColor()
{
return this->color;
}
我之前有一个版本是不用写棋子类的,但是感觉变量挺多的,只能说面向对象和面向过程的相结合,或者除开界面不说,就是面向过程的方法,所以不怎么好理解,思前想后就重写一个比较好的面向对象的方法。