类内/类外重载
#include//类内重载 class InPoint { public: InPoint() {}; InPoint(int x, int y) : x(x), y(y){}; InPoint operator+(const InPoint& b) //运算符作为类的成员函数 { InPoint ret; ret.x = this->x + b.x; ret.y = this->y + b.y; return ret; } int x; int y; }; //类外重载 class OutPoint { public: OutPoint() {}; OutPoint(int x, int y) : x(x), y(y) {}; friend OutPoint operator+(OutPoint a, OutPoint b); int x; int y; }; //类内重载 OutPoint operator+(OutPoint a, OutPoint b) { OutPoint c; c.x = a.x + b.x; c.y = a.y + b.y; return c; } class Point3 { public: Point3() {}; Point3(int x) : x(x) {}; Point3 operator+(int x); int x; }; Point3 Point3::operator+(int x) { Point3 dd; dd.x = this->x + x; return dd; } int main() { InPoint a(2, 3), b(3, 4); InPoint c = a + b; //隐式调用(成员函数) InPoint d = a.operator+(b); //显式调用(成员函数) OutPoint e(3, 4), f(4, 5); OutPoint g = operator+(e, f);//显示调用(友元函数) std::cout << c.x << "; " << c.y << std::endl; Point3 gg(13); Point3 ff = gg + 3; std::cout << "ff = " << ff.x << std::endl; return -1; }



