第19篇 Qt实现简单五子棋游戏(三)棋子类编码

第19篇 Qt实现简单五子棋游戏(三)棋子类编码

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;
}

我之前有一个版本是不用写棋子类的,但是感觉变量挺多的,只能说面向对象和面向过程的相结合,或者除开界面不说,就是面向过程的方法,所以不怎么好理解,思前想后就重写一个比较好的面向对象的方法。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大唐不良猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值