文档详情

《第7章运算符重载9》-课件.ppt

发布:2018-11-08约2.39万字共132页下载文档
文本预览下载声明
第7章 运算符重载 授课内容 7.1 重载概述 7.2 运算符重载 7.3 赋值运算符重载 7.4 ++和--运算符重载 7.5 不同数据类型间的转换 7.1 重载概述 重载概述 函数重载(function overloading ) 允许同个域中的多个函数共享同一个函数名,调用函数时,由编译程序根据实参的形式来选择执行哪个函数。 函数重载例子 #include iostream using namespace std; int abs( int x ) { cout int abs; return x0?x:-x; } double abs( double x ) { cout double abs; return x0?x:-x; } 重载概述 全局域中函数重载的前提 参数个数不同 参数类型不同 不能仅靠函数的返回值类型不同来进行函数重载。 double fun() { return 2.3 } int fun() { return 100; } 函数重载例子 class M { int m_nX; public: M() : m_nX( 0 ) {} M( int a ) : m_nX( a ) {} int F() { return ++m_nX; } int F() const { return m_nX; } }; 重载概述 同一类域中成员函数重载的前提 参数个数不同 参数类型不同 参数形式完全相同的成员函数之间可以通过是否为const成员函数进行重载 构造函数可以重载,析构函数不可重载。 class B { protected: int mb; public: B( int x ): mb(x) {} void Set( int x ) { mb = x; } }; 重载概述 重载函数调用的二义性 C++编译程序无法在多个重载函数中选择正确的函数调用,会导致整个程序无法编译。 例: void func( float c ) { cout c; } void func( double d ) { cout d; } func( 31 ); 7.2 运算符重载 运算符重载 int main { int a = 3 + 5; double b = 3.1 + 4.5; return 0; } 运算符重载 问题的提出: 我们对“+”运算符是否也可以进行了重载,让“+”运算符表达出更多的运算含义。 复数类 class Complex { double R, I; public: Complex(double r=0, double i=0) : R(r), I(i) {} }; 运算符重载 int main() { Complex c1( 1.1, 3.3 ); Complex c2( 4.4, 6.6 ); Complex c3 = c1 + c2; return 0; } class Complex { double R, I; public: Complex(double r = 0,double i = 0):R(r),I(i) {} Complex add( const Complex c ) const { Complex tc; tc.R = R + c.R; tc.I = I + c.I; return tc; } }; 运算符重载 int main() { Complex c1( 1.1, 3.3 ); Complex c2( 4.4, 6.6 ); Complex c3 = c1.add( c2 ); return 0; } class Complex { double R, I; public: Complex(double r = 0,double i = 0):R(r),I(i) {} Complex add(const Complex c) const { Complex temp; temp.R=R+c.R; temp.I=I+c.I; return temp; } }; 运算符重载 int main() { Complex c1( 1.1, 3.3 ); Complex c2( 4.4, 6.6 ); Complex c3 = c1.operator+( c2 ); return 0; } 运算符重载 前面的operator+实质上是Complex的一个成员函数。 这个函数有两
显示全部
相似文档