每天忙于逻辑和技术之外,也需要完善基础的知识体系....
今天学习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引用的好处,在于高效,不声明引用的情况下,参数会进行拷贝,效率不高.