在学习....

每天忙于逻辑和技术之外,也需要完善基础的知识体系....

今天学习C++的运算符重载...

#ifndef POINT_H
#define POINT_H
#include <iostream>
class Point
{
public:
    Point();
    Point(const Point& p);
    Point(int nx, int ny);
    bool isNull() const;


    void setX(int x);
    int x() const;
    void setY(int y);
    int y() const;


    Point &operator +=(const Point &p); //只重载+=, -=,乘除未写出
    Point &operator -=(const Point &p);


    friend inline bool operator==(const Point &, const Point &);
    friend inline bool operator!=(const Point &, const Point &);
    friend inline const Point operator+(const Point &, const Point &);
    friend inline const Point operator-(const Point &, const Point &);


    friend inline std::ostream& operator<<(std::ostream &ot, const Point &);




private:
    int m_x;
    int m_y;
};
inline bool operator==(const Point &a, const Point &b)
{
    return a.x() == b.x() && a.y() == b.y();
}


inline bool operator!=(const Point &a, const Point &b)
{
    return a.x() != b.x() || a.y() != b.y();
}
inline const Point operator+(const Point &a, const Point &b)
{
    Point p;
    p.setX(a.x() + b.x());
    p.setY(a.y() + b.y());
    return p;
}


inline const Point operator-(const Point &a, const Point &b)
{
    Point p;
    p.setX(a.x() - b.x());
    p.setY(a.y() - b.y());
    return p;
}
inline std::ostream& operator<<(std::ostream &ot, const Point &p)
{
    ot << "x:" << p.x() << ",y:" << p.y() << std::endl;
    return ot;
}


#endif // POINT_H
 
自定义了类方便使用
#include "point.h"


Point::Point()
    :m_x(0),m_y(0)
{


}


Point::Point(const Point &p)
{
    this->m_x = p.x();
    this->m_y = p.y();
}


Point::Point(int nx, int ny)
{
    m_x = nx;
    m_y = ny;
}


bool Point::isNull() const
{
    return m_x == 0 && m_y == 0;
}


void Point::setX(int x)
{
    m_x = x;
}


int Point::x() const
{
    return m_x;
}


void Point::setY(int y)
{
    m_y = y;
}


int Point::y() const
{
    return m_y;
}


Point &Point::operator +=(const Point &p)
{
    m_x += p.x();
    m_y += p.y();


    return *this;
}


Point &Point::operator -=(const Point &p)
{
    m_x -= p.x();
    m_y -= p.y();


    return *this;
}
 
理解,自定义数据结构类,在作为函数参数,申明为const引用的好处,在于高效,不声明引用的情况下,参数会进行拷贝,效率不高.
 
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值