C++之重载运算符

在C++随处可见operator重载运算,目前正处于学习C++中,谨以此记录。

什么是函数重载

函数重载是指在同一作用域内,可以有一组具有相同函数名,不同参数列表的函数,这样的函数称为重载函数。重载函数通常用来命名一些功能相似的函数,这样可减少函数命名的数量,避免命名空间的混乱不堪。

函数重载的作用

不言而喻, 不仅可以节省宝贵的命名空间,而且可以使得同一个函数实现多种不同功能。

实例,对运算符重载

对运算符的重载定义如下:
Box operator+(const Box &); 其中Box表示返回类型,+是要重载的运算符号,小括号内的为参数列表。

#include <iostream>
using namespace std;

class complex {
private:
        double real;
        double image;

public:
        complex():real(0.0),image(0.0) {};
        complex(double a,double b):real(a),image(b){};
        friend complex operator+(const complex &A,const complex &B);
        friend complex operator-(const complex &A,const complex &B);
        friend istream & operator>>(istream &in,complex &A);
        friend ostream & operator<<(ostream &out,complex &A);
};

//重载加法运算符
complex operator+(const complex &A,const complex &B)
{
        complex C;
        C.real = A.real + B.real;
        C.image = A.image + B.image;
        
        return C;
}

//重载减法
complex operator-(const complex &A,const complex &B)
{
        complex C;
        C.real = A.real - B.real;
        C.image = A.image - B.image;
        return C;
}
  
//重载输入
istream &operator>>(istream &in,complex &A)
{
        in>>A.real>>A.image;
        return in;
}
ostream & operator << (ostream &out, complex &A) //如果没有重载,就不会输入复数的
{
        out << A.real<<"+"<<A.image<<"i"<<endl;
        return out;
}


int main ()
{
        complex c1,c2,c3;
        cin>>c1>>c2;

        c3 = c1 + c2;
        cout<<"c1 + c2="<<c3<<endl;
        
        c3= c1 - c2;
        cout<<"c1 -c2= "<<c3<<endl;

        cout<<"c1 is:"<<c1<<endl;

        return 0;
        
}

上面的重载运算符实现了复数的加减和输入输出功能。

再来看一个更好玩的(引自实验室“扫地僧”)

#include <iostream>
using namespace std;

class boss {
public:
        boss(const char *str) {info = str;}
        boss(string s) {info = s;}
        boss operator+(const boss &b) {
                if (!info.compare("习大") && !b.info.compare("奥黑")) {
                        return boss("安倍好捉急!");
                } else {
                        return boss(this->info + b.info);
                }
        }
public:  //注意:这里为public成员,所以"operator<<"不必声明为类的友元函数
        string info;
};

ostream & operator<<(ostream &os, const boss &b) {
        os << b.info << endl;
        return os;
}

int main(void)
{
        boss xi_da("习大");
        boss ao_hei("奥黑");
        cout << xi_da + ao_hei << endl;
        return 0;
}

如果运行上面的程序,它会输出安倍好捉急,是不是很有意思!

总结

函数重载或是运算符重载的出现,可以使得自己定制个性化的程序,并能使得同样函数名的程序实现不同的功能,总之,它的出现为人类进步做出了巨大贡献,感谢开发者!

一些相关链接:
http://www.runoob.com/cpluspl…
C语言中文网
吴秦的博客

    原文作者:SimpleTriangle
    原文地址: https://segmentfault.com/a/1190000006971869
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞