文档介绍:第13章 运算符重载
第1页/共240页
讲授内容
运算符重载的概念
以成员函数的方式重载运算符
以友元函数的方式重载运算符
流插入和流提取运算符的重载
一般单目和双目运算符的重载
赋值运算符重载
类型转换运算符重载
第2页/共240页
运算符重载的概念 (1/2)
类似于函数重载
把传统的运算符用于用户自定义的对象
直观自然,可以提高程序的可读性
体现了C++的可扩充性
通过定义名为operator <运算符>的函数来实现运算符重载
第3页/共240页
例1 :复数的+、-、=运算 (1/5)
// 文件1:--复数类的定义
#ifndef COMPLEX1_H
#define COMPLEX1_H
class Complex {
public:
Complex(double = , double = );
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
第4页/共240页
例1 :复数的+、-、=运算 (2/5)
//文件2:--复数类的成员函数定义
#include <>
#include ""
Complex::Complex(double r, double i)
{ real = r;
imaginary = i;
}
Complex Complex::operator+(const Complex &operand2) const
{
Complex sum;
= real + ;
=imaginary + ;
return sum;
}
第5页/共240页
例1 :复数的+、-、=运算 (3/5)
Complex Complex::operator-(const Complex &operand2) const
{
Complex diff;
= real - ;
=imaginary - ;
return diff;
}
Complex& Complex::operator=(const Complex &right)
{
real = ;
imaginary = ;
return *this; // enables concatenation
}
void Complex::print() const
{ cout<<'('<<real<< ", " << imaginary << ')'; }
第6页/共240页
例1 :复数的+、-、=运算 (4/5)
//文件3: --主函数定义
#include <>
#include ""
main()
{
Complex x, y(, ), z(, );
cout << "x: ";
();
cout << "\ny: ";
();
cout << "\nz: ";
();
x = y + z;
cout << "\n\nx = y + z:\n";
第7页/共240页
例1 :复数的+、-、=运算 (5/5)
();
cout << " = ";
();
cout << " + ";
();
x = y - z;
cout << "\n\nx = y - z:\n";
();
cout << " = ";
();
cout