- 1、本文档共46页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
c6操作符重载
操作符重载 重载就是相同的名称或符号具有不同的意义。 重载 : 函数重载和操作符重载。 操作符重载有两种形式:类的成员函数方式和顶层函数方式 6.1 基本操作符重载 操作符有一元操作符和二元操作符。 下列操作符不能被重载: 成员选择符(.)、成员对象选择符(.*)、域解析操作符(::)和条件操作符(?:)。 赋值操作符(=)不能被派生类所继承。 下标操作符[]、赋值操作符=、函数调用操作符()和指针操作符-必须以类的成员函数的形式进行重载 class C { public: C operator + ( const C ) const; //... }; C C::operator + (const C c) const { //... } C a, b, c; a = b.operator + ( c ); a = b + c; 例子:一元操作符! 和 二元操作符 = class C { public: C operator= (const C); C operator ! (); //... }; 6.1.1 操作符的优先级和语法 重载不能改变操作符的优先级和语法。 如果一个内建操作符是一元的,那么所有对它的重载仍是一元的。如果一个内建操作符是二元的,那么所有对它的重载仍是二元的。 class C { public: C operator % ( ); }; 6.2 示例程序:复数类 要求: 1。重载+、-、* 和 /,以支持复数的算术运算 2。设计一个write函数,以输出一个复数至标准输出 3。设计默认构造函数,将实部和虚 部设为零 4。设计拥有一个参数的构造函数,将实部设为该参数,虚部设为零 5。设计拥有两个参数的构造函数,将两个参数分别赋给实部和虚部。 Complex类的实现 class Complex { public: Complex(); // default Complex( double ); // real given Complex( double, double ); // both given void write() const; // operator methods Complex operator+( const Complex ) const; Complex operator-( const Complex ) const; Complex operator*( const Complex ) const; Complex operator/( const Complex ) const; private: double real; double imag; }; // default constructor Complex::Complex() { real = imag = 0.0; } // constructor -- real given but not imag Complex::Complex( double re ) { real = re; imag = 0.0; } // constructor -- real and imag given Complex::Complex( double re, double im ) { real = re; imag = im; } void Complex::write() const { cout real + imag i; } // Complex + as binary operator Complex Complex::operator+( const Complex u ) const { Complex v( real + u.real, imag + u.imag ); return v; } // Complex - as binary operator Complex Complex::operator-( const Complex u ) const { Complex v( real - u.real, imag - u.imag ); return v; } // Complex * as binary operator Complex Complex::operator*( const Complex u )const {
文档评论(0)