C++中操作符重载

    C++中出了能进行函数重载,还能对操作符进行重载,在分析操作符重载之前,我们先来看看下边的代码:
 

#include <iostream>
#include <string>

using namespace std;

class Complex	//定义一个复数类
{
private:
    int i;
    int j;

public:
    Complex(int m, int n)
    {
    	this->i = m;
    	this->j = n;
    }

    int getI()
    {
    	return i;
    }

    int getJ()
    {
    	return j;
    }
};


int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);

    Complex c3;
    c3 = c1 + c2;	//我们希望的是,能够像数值加减一样对对象也能进行加减,最终 c3的i\j变量分别为4和6

    system("pause");
}

实则编译是无法通过的,因为C++中并没有对象与对象之间直接进行加法的操作,要解决这个问题,就需要我们实现C++中的运算符重载操作。

    -C++中的重载能够扩展操作符的功能
    -操作符的重载是以函数的方式进行
    -用特殊形式的函数扩展操作符的功能

C++中通过operator关键字可以定义特殊的函数,本质是通过这个特殊的函数来重载操作符
语法如下:

有了以上知识,我们来对上边代码进行修改,在全局区实现一个“+”操作符的重载
 

#include <iostream>
#include <string>

using namespace std;

class Complex	//定义一个复数类
{
public:
    int i;
    int j;

public:
    Complex(){}
    Complex(int m, int n)
    {
    	this->i = m;
    	this->j = n;
    }

    int getI()
    {
    	return i;
    }

    int getJ()
    {
    	return j;
    }
};

//在全局区实现加法操作符重载
Complex operator + (Complex c1, Complex c2)
{
    Complex c;
    c.i = c1.i + c2.i;
    c.j = c1.j + c2.j;

    return c;
}


int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);

    Complex c3;
    c3 = c1 + c2;	//直接对两个Complex对象相加

    cout << "c3.getI() = " << c3.getI() << endl;
    cout << "c3.getJ() = " << c3.getJ() << endl;

    system("pause");
}

我们来编译输出如下:

到这里,其实我们想要的功能已经实现了,但是任然可以做一些优化
在C++中可以将操作符重载函数定义为类的成员函数
     -比全局操作符重载函数少一个参数(左操作数)
     -编译器优先在成员函数中寻找操作符重载函数

现在我们再来修改一下,把操作符重载在类中实现
 

#include <iostream>
#include <string>

using namespace std;

class Complex	//定义一个复数类
{
private:
    int i;
    int j;

public:
    Complex(){}
    Complex(int m, int n)
    {
    	this->i = m;
    	this->j = n;
    }

    //将操作符重载实现为类成员函数
    Complex operator + (Complex c)
    {
    	Complex ret;
    	ret.i = this->i + c.i;
    	ret.j = this->j + c.j;

    	return ret;
    }

    int getI()
    {
    	return i;
    }

    int getJ()
    {
    	return j;
    }
};

int main()
{
    Complex c1(1, 2);
    Complex c2(3, 4);

    Complex c3;
    c3 = c1 + c2;	//直接对两个Complex对象相加

    cout << "c3.getI() = " << c3.getI() << endl;
    cout << "c3.getJ() = " << c3.getJ() << endl;

    system("pause");
}

编译输出如下:

到这里,操作符重载,基本介绍完成了,当然可以举一反三,这里的“+”,可以换成“-” 、“*”、“/”

总结:
    -操作符重载是C++的强大特性之一
    -操作符重载的本质是通过函数扩展操作符的功能
    -operator关键字是实现操作符重载的关键
    -操作符重载遵循相同的函数重载规则
   -全局函数和成员函数都可以实现对操作符的重载

猜你喜欢

转载自blog.csdn.net/lms1008611/article/details/81428366