} 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˼¿¼Ìâ £±£®¶¨Òå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