18.2如何重载运算符类A对象加法例18-3:class A1;//两个A类对象参加运算,返回int型值int operator+(A&,A&);C++规定,运算符中参数说明都是内部类型时,不能重载int *operator +(int, int *);C++基本数据类型之间的关系是确定的,如果允许定义其上的新操作,那么会导致关系混乱
例18-3:类A对象加法 class A { } ; //两个A类对象参加运算,返回int型值 int operator + ( A & , A & ) ; • C++规定,运算符中参数说明都是内部类型时, 不能重载。 int * operator + ( int , int * ) ; • C++基本数据类型之间的关系是确定的,如果允 许定义其上的新操作,那么会导致关系混乱
18.2如何重载运算符4、C++中不允许重载的运算符运算符运算符名称?:三目条件运算符成员操作符作用域操作符*访问指针内容的运算符成员指针操作符注*作为指针说明符及乘法运算符可重载
4、C++中不允许重载的运算符。 运算符 运算符名称 ? : 三目条件运算符 . 成员操作符 :: 作用域操作符 * -> 访问指针内容的运算符 成员指针操作符 注 * 作为指针说明符及乘法运算符可重载
如何重载运算符18.2 t例18 4:定义一个复数类,并重载加法运算符#ifndefCOMPLEX#defineCOMPLEXclass Complexprivate :double real, imag ;public :Complex (double r = 0, double i = 0) : real(r), imag(i) ( )double Real() ( return real; )double Imag() ( return imag; )&能去掉吗?Complex operator+(Complex&);Complex operator + (double) ;Complex operator=(Complex);#endif
例18_4:定义一个复数类,并重载加法运算符 #ifndef COMPLEX #define COMPLEX class Complex { private : double real, imag ; public : Complex (double r = 0, double i = 0) : real(r), imag(i) { } double Real( ) { return real; } double Imag( ) { return imag; } Complex operator + ( Complex & ) ; // &能去掉吗? Complex operator + (double) ; Complex operator = ( Complex ) ; } ; #endif
18.2如何重载运算符/重载运算符十Complex Complex::operator + (Complex &cComplex temp;temp.real = real+c.real:temp.imag = imag+c.imag:return temp;Complex Complex :: operator + (double d)/重载运算符十YComplex temp;temp.real = real + d :temp.imag = imag:return temp;
// 重载运算符 + Complex Complex::operator + (Complex &c) { Complex temp; temp.real = real+c.real; temp.imag = imag+c.imag; return temp; } Complex Complex :: operator + (double d) // 重载运算符+ { Complex temp; temp.real = real + d ; temp.imag = imag; return temp; }
18.2如何重载运算符Complex Complex::operator=(Complex c)// 重载运算符=real = c.real;imag = c.imag,return * this ;// this指针,相当于默认对象1void main()(Complex c1(3, 4), c2(5, 6), c3 ;cout <<"cl =" << ci.Real() <<"+" << cl.Imag() <<"+i In";cout <<"c2 =" << c2.Real() <<"+" << c2.Imag0) <<"+i In ";c3 = c1+c2;cout <<"c3 = " << c3.RealO << "+" << c3.Imag) <<"+ i In ";c3 = c3+6.5;cout <<"c3 + 6.5 = " << c3.RealO <<"+" << c3.Imag0) "+ i ln ";1
Complex Complex::operator = ( Complex c ) // 重载运算符= { real = c.real; imag = c.imag; return * this ; // this 指针,相当于默认对象 } void main( ) { Complex c1(3, 4), c2(5, 6), c3 ; cout << "c1 = " << c1.Real() << "+" << c1.Imag() << "+i \n"; cout << "c2 = " << c2.Real() << "+" << c2.Imag() << "+i \n "; c3 = c1+c2; cout << "c3 = " << c3.Real() << "+" << c3.Imag() << "+ i \n "; c3 = c3+6.5; cout << "c3 + 6.5 = " << c3.Real() << "+" << c3.Imag() "+ i \n "; }