} CComplex(float x, float y) { real = x; imag = y; } CComplex operator + (CComplex &obj1) { CComplex obj2(real + obj1.real, imag + obj1.imag); return obj2; } friend CComplex operator++(CComplex &obj) { obj.real += 1; obj.imag += 1; return obj; } CComplex operator--(); void print() { cout << real << \ } private: float real; float imag; };
CComplex CComplex::operator--() { real -= 1; imag -= 1; return (*this); }
void main() { CComplex obj1(2.1, 3.2); CComplex obj2(3.6, 2.5);
20
cout << \ obj1.print(); cout << \ obj2.print(); CComplex obj3 = obj1 + obj2; cout << \ obj3.print(); ++obj3; cout << \ obj3.print(); --obj3; cout << \ obj3.print(); CComplex obj4 = ++obj3; cout << \ CComplex obj4.print(); }
结果:
obj1=2.1+3.2; obj2=3.1+2.5; obj3=5.7+5.7;
after++obj3=1.7+1.7; after--obj3=5.7+5.7; obj4=1.7+1.7;
7.2.2 程序设计
1.把7.2.1中第一道题的程序改造成采取友元函数重载方式来实现“+”运算符,并采取友元函数重载方式增加前置和后置“++”以及“--”运算符重载,并设计主函数来验证重载运算符的用法。
#include
21
} CComplex(int x,int y) { real=x; imag=y; } friend CComplex operator+(CComplex obj1,CComplex obj2) { return CComplex(obj1.real-obj2.real,obj1.imag-obj2.imag); } friend CComplex operator++(CComplex obj) { obj.real+=1; obj.imag+=1; return(*this); } friend CComplex operator+(CComplex obj1,CComplex obj2) { return CComplex(obj1.real-obj2.real,obj1.imag-obj2.imag); } int real; int imag; }
void show() { cout< void main() { CComplex obj1(1,2); CComplex obj2(3,4); CComplex obj; obj=obj1+obj2; obj.show(); ++obj; obj.show(); obj=obj1-obj2; 22 } obj.show(); return 0; 7.3思考题 1.定义CPoint类,有两个成员变量:横坐标(x)和纵坐标(y),对CPoint类重载“++”(自增运算符)、“--”(自减运算符),实现对坐标值的改变。(每个函数均采用友元禾成员函数实现) #include public: int x; int y; CPoint() { x=0; y=0; } CPoint(int x,int y) { x=x1; y=y2; } friend CPoint operator++(CPoint obj); { obj.x+=1; obj.y+=1; return (*this); } friend CPoint operator--(CPoint obj); { obj.x-=1; obj.y-=1; return (*this) } 23 int x; int y; } void show() { cout<<\} void main() { CPoint obj(1,2); obj.show(); obj++; obj.show(); obj--; obj.show(); return 0; } 24