复习笔记(六)——C++运算符重载(难点)

运算符重载

运算符重载的概念

运算符重载类似于函数重载。

运算符重载允许把标准运算符(如+-*<等)应用于定制数据类型的对象。

什么情况下需要考虑运算符重载?
需要用运算符操作自定义类的对象时,如对象之间直观自然,可以提高比较大小等,通过重载支持类的运算。

运算符重载:①体现了程序的可读性;②体现了C++的可扩充性

运算符重载的定义

作为类的成员函数或友元函数、作为一般函数(很少用)。

1、成员函数原型的格式:
函数类型 operator 运算符(参数表);
成员函数定义的格式:

函数类型 类名::operator 运算符(参数表)
{
   
	函数体;
}

以成员函数的方式重载运算符
-单目运算符:不带参数,该类对象为唯一操作数
-双目运算符:带一个参数,该类对象为左操作数、参数为右操作数


2、友元函数原型的格式:
friend 函数类型 operator 运算符(参数表);
友元函数定义的格式:

函数类型 operator 运算符(参数表)
{
   
	函数体;
}

以友元函数的方式重载运算符
-单目运算符:带一个参数,该参数为唯一操作数,是自定义类的对象 ++(a)
-双目运算符:带两个参数,第一个参数为左操作数、第二个参数为右操作数,至少有一个参数为自定义类的对象
+(a, b)

实例

#include 
using namespace std;

class Complex
{
   
public:
    Complex(double = 0.0, double = 0.0);
    Complex operator+(const Complex&) const;
    Complex Add(const Complex&) const;
    Complex operator-(const Complex&) const;
    Complex& operator=(const Complex&);
    void print() const;
private:
    double real;       // real part
    double imaginary;  // imaginary part
};
Complex::Complex(double r, double i)
{
   
    real = r;
    imaginary = i;
}
Complex Complex::operator+(const Complex &operand2) const
{
   
  Complex sum;
  sum.real = this->real + operand2.real;
  sum.imaginary= this->imaginary + operand2.imaginary;
  return sum;
}
Complex Complex::Add(const Complex &operand2) const
{
   
    //功能的实现同上
}
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 << ')';
}
int 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;	//比表达式x=y.Add(z);更简练,更直观
    cout << "\n\nx = y + z:\n";	x.print();
    cout << " = ";		y.print();
    cout << " + ";		z.print();

    return 0;
}

执行结果:

x: (0,0)
y: (4.3,8.2)
z: (3.3,

你可能感兴趣的:(复习笔记(六)——C++运算符重载(难点))