第13部分运算符重载课程.pptVIP

  • 4
  • 0
  • 约1.18万字
  • 约 54页
  • 2016-12-04 发布于江苏
  • 举报
第13章 运算符重载 讲授内容 运算符重载的概念 以成员函数的方式重载运算符 以友元函数的方式重载运算符 流插入和流提取运算符的重载 一般单目和双目运算符的重载 赋值运算符重载 类型转换运算符重载 13.1 运算符重载的概念 (1/2) 类似于函数重载 把传统的运算符用于用户自定义的对象 直观自然,可以提高程序的可读性 体现了C++的可扩充性 通过定义名为operator 运算符的函数来实现运算符重载 例1 :复数的+、-、=运算 (1/5) // 文件1:complex1.h--复数类的定义 #ifndef COMPLEX1_H #define COMPLEX1_H class Complex { public: Complex(double = 0.0, double = 0.0); Complex operator+(const Complex) const; Complex operator-(const Complex) const; Complex operator=(const Complex); void print() const; private: double real; // real part double imaginary; // imaginary part }; #endif 例1 :复数的+、-、=运算 (2/5) //文件2:complex1.cpp--复数类的成员函数定义 #include iostream.h #include complex1.h Complex::Complex(double r, double i) { real = r; imaginary = i; } Complex Complex::operator+(const Complex operand2) const { Complex sum; sum.real = real + operand2.real; sum.imaginary=imaginary + operand2.imaginary; return sum; } 例1 :复数的+、-、=运算 (3/5) Complex Complex::operator-(const Complex operand2) const { Complex diff; diff.real = real - operand2.real; diff.imaginary=imaginary - operand2.imaginary; return diff; } Complex Complex::operator=(const Complex right) { real = right.real; imaginary = right.imaginary; return *this; // enables concatenation } void Complex::print() const { cout(real , imaginary ); } 例1 :复数的+、-、=运算 (4/5) //文件3: FIG13_1.cpp--主函数定义 #include iostream.h #include complex1.h main() { Complex x, y(4.3, 8.2), z(3.3, 1.1); cout x: ; x.print(); cout \ny: ; y.print(); cout \nz: ; z.print(); x = y + z; cout \n\nx = y + z:\n; 例1 :复数的+、-、=运算 (5/5) x.print(); cout = ; y.print(); cout + ; z.print(); x = y - z; cout \n\nx = y - z:\n; x.print(); cout = ; y.print(); cout - ; z.print(); cout \n; return 0; } 程序执行结果: x: (0, 0) y: (4.3, 8.2) z: (3.3, 1.1) x = y + z: (7.6, 9.3) = (4.3, 8.2) + (3.3, 1.1) x = y - z: (1, 7.1) =

文档评论(0)

1亿VIP精品文档

相关文档