定义一个二维平面的点类CPoint,包含两个坐标属性,请完成如下功能:
1.定义一个带默认参数值的构造函数,参数默认值都为0.
2.定义一个前自增运算符重载函数,要求实现CPoint对象的两个坐标分别加1。
3.定义一个后自增运算符重载函数,要求实现CPoint对象的两个坐标分别加1。
4.定义一个加法运算符重载函数,要求实现CPoint对象的两个坐标分别加上一个实数。
5.定义一个流插入运算符重载函数。
6.编程CPoint类的测试程序。
具体代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
#include "stdafx.h" #include <iostream> using namespace std; class CPoint { private: int x; int y; public: CPoint() :x(0), y(0) {} CPoint(int x_, int y_) :x(x_), y(y_) {} CPoint(CPoint& p) :x(p.x), y(p.y) {} ~CPoint() {} CPoint& operator++() { ++x; ++y; return *this; } CPoint operator++(int)//提醒编译器后加 { CPoint temp(*this); ++x; ++y; return temp; } CPoint operator+(const float& f) { x += f; y += f; return *this; } friend ostream& operator<<(ostream & os, const CPoint& Point); }; ostream& operator<<(ostream& os, const CPoint& Point) { os <<"X:"<< Point.x <<"Y:" << Point.y << endl; return os; } int main() { CPoint Point1(1,2),Point2(10,20); Point1 = Point1 + 1; Point2 = Point2 + 2; cout << Point1 << endl; cout << Point2 << endl; ++Point1; Point2++; cout << Point1 << endl; cout << Point2 << endl; system("pause"); return 0; } |
运行结果: