#include #include #include #include #include #include #include #include #include #include using namespace std; class Point { public: Point(); Point(int x, int y); //类内重载 Point operator+(const Point &); Point &operator+=(int); int operator[](string); int getX() {return x; } int getY() {return y; } private: friend Point operator+(const Point &, const Point &); friend ostream &operator<<(ostream &, const Point &); int x, y; }; class PPoint { public: PPoint(Point *p) : p(p) {} Point *operator->() {return p;} private: Point *p; }; class ADD { public: ADD(int c) : c(c) {} int operator()(int a, int b) { return a + b + c; } private: int c; }; //委托构造函数 Point::Point() : Point(0, 0) {} Point::Point(int x, int y) : x(x), y(y) {} //数组对象 int Point::operator[](string s) { if (s == "x") return x; if (s == "y") return y; return 0; } ostream &operator<<(ostream &out, const Point &a) { out << "(" << a.x << "," << a.y << ")"; return out; } Point &Point::operator+=(int n){ x += n, y += n; return *this; } //类内重载 Point Point::operator+(const Point &a) { cout << "inner operator+" << endl; Point c(x + a.x, y + a.y); return c; } //类外重载 Point operator+(const Point &a, const Point &b) { cout << "outer operator+" << endl; Point c(a.x + b.x, a.y + b.y); return c; } int main() { ADD add(5);//仿函数,可调用对象 cout << add(6, 7) << endl; Point a(3, 4); Point b(7, 9); cout << a["x"] << endl;//数组对象 cout << a["y"] << endl; Point c = a + b; cout << a << endl; cout << b << endl; cout << c << endl; (a += 3) += 2;//x和y统一加上3,再加上2 cout << a << endl; PPoint p = &a; cout << p->getX() << " " << p->getY() << endl; return 0; }
18 3 4 inner operator+ (3,4) (7,9) (10,13) (8,9) 8 9
上一篇 [C++实验2 ]继承和多态
下一篇 2021-11-01
版权所有 (c)2021-2022 MSHXW.COM
ICP备案号:晋ICP备2021003244-6号