重载函数operator+- 个是his指针指向 一个是形参对 的对象中的成员 象中的成员 ↓ ↓ this->real就是cl.real c2.real this->real+c2.real=c1->real+c2.real c1+c2 cl.operator-±(c2) Complex(c1.real c2.real,c1.imag+c2.imag))
重载函数operator+ 一个是this指针指向 的对象中的成员 一个是形参对 象中的成员 this->real就是c1.real c2.real this->real+c2.real= c1->real+c2.real c1+c2 c1.operator+(c2) Complex(c1.real + c2.real,c1.imag+c2.imag))
例10.3将运算符“+”重载为适用于复数加法,重载函数 不作为成员函数,而放在类外,作为Complex类的友元函 粘 #include <iostream> using namespace std; class Complex public: Complex()freal=0;imag=0;} Complex(double r,double i) (real=r;imag-i;) friend Complex operator +(Complex &c1,Complex &c2); void display()为 private: 重载函数作为友元函数 double real; double imag;
例10.3 将运算符“+”重载为适用于复数加法,重载函数 不作为成员函数,而放在类外,作为Complex类的友元函 数 #include <iostream> using namespace std; class Complex {public: Complex( ){real=0;imag=0;} Complex(double r,double i) {real=r;imag=i;} friend Complex operator + (Complex &c1,Complex &c2); void display( ); private: double real; double imag; }; 重载函数作为友元函数
定义作为友元函数的重载函数 Complex operator +(Complex &c1,Complex &c2) (return Complex(c1.real+c2.real,c1.imag+c2.imag);} void Complex:display() {cout<<"("<<real<<","<<imag<<"i)"<<endl,) int main( 与例10.2相比较 {Complex c1(3,4),c2(5,-10),c3: 将运算符函数不 c3-c1+c2; 作为成员函数 cout<<"c1=";c1.display(); cout<<"c2=";c2.display(); 放在类外,在Complex cout<<"c1+c2 ="c3.display() 类中声明它为友元函数 运算符函数改为有两个参数
Complex operator + (Complex &c1,Complex &c2) {return Complex(c1.real+c2.real, c1.imag+c2.imag);} int main( ) {Complex c1(3,4),c2(5,-10),c3; c3=c1+c2; cout<<″c1=″; c1.display( ); cout<<″c2=″; c2.display( ); cout<<″c1+c2 =″; c3.display( ); } void Complex∷display( ) {cout<<″(″<<real<<″,″<<imag<<″i)″<<endl;} 定义作为友元函数的重载函数 与例10.2相比较 将运算符函数不 作为成员函数 放在类外,在Complex 类中声明它为友元函数 运算符函数改为有两个参数
程序中的表达式cl+c2解释为 operator+(c1.c2) Complex operator +(Complex &c1,Complex &c2) return Complex(c1.real+c2.real,c1.imag+c2.imag); 运算符函数 ◆运算符函数要访问Complex类对象中的成员 为什么作为 友元函数 运算符函数不是Complex类的 友元函数而是一个普通的函数 没有权利访问Complex类的 私有成员的
程序中的表达式c1+c2解释为 operator+(c1,c2) Complex operator + (Complex &c1,Complex &c2) {return Complex(c1.real+c2.real, c1.imag+c2.imag);} 运算符函数 为什么作为 友元函数 运算符函数要访问Complex类对象中的成员 运算符函数不是Complex类的 友元函数而是一个普通的函数 没有权利访问Complex类的 私有成员的
运算符重载函数 极少的情况下才使用普通函数 不能直接访问类的私有成员 运算符重载函数 通过ths指针自由地访问本类的数据成员 作为成员函数 少写一个函数的参数 但必须要求运算表达式第一个参数(即 运算符左侧的操作数)是一个类对象,而 且与运算符函数的类型相同
运算符重载函数 极少的情况下才使用普通函数 不能直接访问类的私有成员 运算符重载函数 作为成员函数 通过this指针自由地访问本类的数据成员 少写一个函数的参数 但必须要求运算表达式第一个参数(即 运算符左侧的操作数)是一个类对象,而 且与运算符函数的类型相同