技术交流QQ群:1027579432,欢迎你的加入!

1.C++中的运算符重载基础

  • 所谓重载,就是赋予新的含义。函数重载(Function Overloading)可以让一个函数名有多种功能,在不同情况下进行不同的操作。运算符重载(Operator Overloading)也是一个道理,同一个运算符可以有不同的功能。下面的代码定义了一个复数类,通过运算符重载,可以用+号实现复数的加法运算:
        #include "iostream"
    
        using namespace std;
    
        class Complex{
            public:
                Complex();
                Complex(double a, double b);
                // 运算符重载声明
                Complex operator+(const Complex &A) const;
                void show() const;  // 常成员函数
            private:
                double real;
                double img;
        };
    
        // 默认构造函数初始化
        Complex::Complex():real(0.0), img(0.0){};
        // 带参数构造函数初始化
        Complex::Complex(double a, double b):real(a), img(b){};
        // 实现运算符的重载
        Complex Complex::operator+(const Complex &A) const{
            Complex B;
            B.real = this->real + A.real;
            B.img = this->img + A.real;
            return B;
        }
    
        void Complex::show() const{
            cout << real << " + " << img << "i" << endl;
        }
    
    
    
    
        int main(){
            Complex c1(4.3, 5.8);
            Complex c2(4.3, 5.8);
            Complex c3;
            c3 = c1 + c2;
            c3.show();
            return 0;
        }
    
  • 运算符重载其实就是定义一个函数,在函数体内实现想要的功能,当用到该运算符时,编译器会自动调用这个函数。也就是说,运算符重载是通过函数实现的,它本质上是函数重载。
  • 运算符重载的格式为:
        返回值类型 operator 运算符名称 (形参列表){
            // TODO;
        }
    
  • operator是关键字,专门用于定义重载运算符的函数。可以将operator运算符名称这一部分看做函数名,对于上面的代码,函数名就是operator+。运算符重载函数除了函数名有特定的格式,其它地方和普通函数并没有区别。

2.在全局范围内重载运算符

  • 运算符重载函数不仅可以作为类的成员函数,还可以作为全局函数。更改上面的代码,在全局范围内重载+,实现复数的加法运算
        #include "iostream"
    
        using namespace std;
    
    
    
        // 2. 全局范围内重载运算符
        class complex{
        public:
            complex();
            complex(double a, double b);
        public:
            void show() const;
            //声明为友元函数
            friend complex operator+(const complex &A, const complex &B);
        private:
            double real;
            double img;
        };
    
    
        complex::complex(): real(0.0), img(0.0){ }
        complex::complex(double a, double b): real(a), img(b){ }
        void complex::show() const{
            cout << real <<" + "<< img << "i"<<endl;
        }
        //在全局范围内重载+
        complex operator+(const complex &A, const complex &B){
            complex C;
            C.real = A. real + B.real;
            C.img = A.img + B.img;
            return C;
        }
    
    
    
        int main(){
            complex x1(3.9, 4.2);
            complex x2(3.9, 4.2);
            complex x3;
            x3 = x1 + x2;
            x3.show();
            return 0;
        }