C++课件 第十三章 运算符重载.ppt





《C++课件 第十三章 运算符重载.ppt》由会员分享,可在线阅读,更多相关《C++课件 第十三章 运算符重载.ppt(35页珍藏版)》请在淘文阁 - 分享文档赚钱的网站上搜索。
1、第十三章 运算符重载运算符一种函数;对于类对象,用户可重新定义运算符函数。class C private:double x;public:C()x=0.0;C(double a)x=a;C add(const C m)C temp;temp.x=m.x+x;return temp;引子 C a(10),b(3);C c=a.add(b);希望希望c=a+b;C a(10),b(3),c;c=a+b;赋值运算符一般用预定义的赋值运算符一般用预定义的a.operator+(b)加法运算符重载函数(利用利用成员函数重载成员函数重载)class C /public:C operator+(C m)C
2、temp(x+m.x);return temp;/;/定义方式1.负号负号“-”(利用利用成员函数重载成员函数重载)C C:operator-()C temp;temp.x=-x;return temp;一.单目运算符重载 C c=-a;a.operator-()1.负号负号“-”(利用友元利用友元函数重载函数重载)class C /public:friend C operator-(const C);/;C operator-(const C m)C temp;temp.x=-m.x;return temp;C c=-a;operator-(a)单目运算符重载中成员函数重载与友元函数重载之间
3、的区别:n 用成员函数重载单目运算符,由于此时运算符的操作数为当前对象,因此用成员函数重载单目运算符时无参数。n 由于友元函数非成员函数,不能使用this指针,因此用友元函数重载单目运算符时必须带有一个参数作为该运算符的操作数。2.前置运算符前置运算符+(利用利用成员函数重载成员函数重载)class C private:double x;public:C()x=0.0;C(double a)x=a;C operator+()x+;return*this;C A(1);+A;2.前置运算符前置运算符+(利用友元利用友元函数重载函数重载)class C private:double x;publi
4、c:C()x=0.0;C(double a)x=a;friend C operator+(C&);C operator+(C&t)t.x+;return t;C A(1);+A;对于要改变操对于要改变操作数的运算符作数的运算符(比如比如+、-等等),参数必,参数必须是引用类型或指须是引用类型或指针类型针类型。3.后置运算符后置运算符-(利用利用成员函数重载成员函数重载)class C private:double x;public:C()x=0.0;C(double a)x=a;C operator-(int)x-;return*this;C A(1);A-;整型参数没有整型参数没有特别的意义
5、,只是特别的意义,只是标识重载的是后置标识重载的是后置运算符。运算符。3.后置运算符后置运算符-(利用友元利用友元函数重载函数重载)class C private:double x;public:C()x=0.0;C(double a)x=a;friend C operator-(C&,int);C operator-(C&t,int)t.x-;return t;C A(1);A-;整型参数没有整型参数没有特别的意义,只是特别的意义,只是标识重载的是后置标识重载的是后置运算符。运算符。class C private:double x;public:C()x=0.0;C(double a)x=a
6、;friend C operator-(C t)t.x-;return t;void show()coutxendl;void main()C c(5.6);(-c).show();c.show();例:程序输出结果?4.65.61.加号加号+(利用利用成员函数重载成员函数重载)C C:operator+(C m)C temp;temp.x=x+m.x;return temp;二.双目运算符重载C a,b;C c=a+b;a.operator+(b)1.加号加号+(利用友元利用友元函数重载函数重载)先在类中声明:friend C operator+(C,C);再在类外定义:C operator
7、+(C m1,C m2)C temp;temp.x=m1.x+m2.x;return temp;C a,b;C c=a+b;operator+(a,b)2.乘号乘号*(利用利用成员函数重载成员函数重载)C C:operator*(C m)C temp;temp.x=x*m.x;return temp;C a,b;C c=a*b;a.operator*(b)2.乘号乘号*(利用友元利用友元函数重载函数重载)先在类中声明:friend C operator*(C,C);再在类外定义:C operator*(C m1,C m2)C temp;temp.x=m1.x*m2.x;return temp;
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C+课件 第十三章 运算符重载 C+ 课件 第十三 运算 重载

限制150内