运算符重载之加法运算

目的:计算两个类之间实部的相加和虚部的相加。如定义类c1,  c2(1,2),   c3(2,3),计算c1=c2+c3  ,  需要实现的效果为:  c1(1+2 , 2+3) 。

差异:普通运算规则在C++中可以识别,但类的运算却不能,需要人为规定好规则。个人认为,运算符重载本质就是把普通的运算规则封装,方便给用户拓展。

语法:  例如  Complex operator+(Complex &c1, Complex &c2)

如下代码:

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>
using namespace std;

class A
{
public:
    A()
    {

    }
    A(int a,int b )
    {
        this->a = a;
        this->b = b;
    }
    ~A()
    {
    }
    void printCom()
    {
        cout << a << " + " << b << "i" << endl;
    }
public:
    int a;
    int b;
protected:
private:
};
//普通运算规则实现函数功能
A myAdd(A &c1, A &c2)//引用类
{
    A tmp(c1.a + c2.a, c1.b + c2.b);
    return tmp; //
}
void main()
{
    A c1(1,2),c2(3,4);
         //实现目的:
    A c3 = myAdd(c1, c2);//运用普通运算规则
    c3.printCom();


    system("pause");
    return;
}
View Code

运算符重载后,如下代码:

#define  _CRT_SECURE_NO_WARNINGS 
#include <iostream>
using namespace std;

class A
{
public:
    A()
    {

    }
    A(int a,int b )
    {
        this->a = a;
        this->b = b;
    }
    ~A()
    {
    }
    void printCom()
    {
        cout << a << " + " << b << "i" << endl;
    }
public:
    int a;
    int b;
protected:
private:
};
//普通规则计算
A myAdd(A &c1, A &c2)//引用类
{
    A tmp1(c1.a + c2.a, c1.b + c2.b);
    return tmp1; 
}
//运算符重载
A operator+(A &c1, A &c2)
{
    A tmp2(c1.a + c2.a, c1.b + c2.b);
    return tmp2; 
}
void main()
{
    A c1(1,2),c2(3,4);
    //A c3 = myAdd(c1, c2);//普通规则调用
    A c3 = operator+(c1, c2);//重载运算符规则
    c3.printCom();
    system("pause");
    return;
}
View Code

在main函数里,可以把A  c1 = operator+(c2, c3) 简化成为A c1 = c2 + c3  ,它也能识别,其结果是一样的。

有了operator关键字修饰的函数后,当调用时,系统会自动识别operator关键字所修饰的函数名从而实现加法规则运算。

有意思的是,运算符重载函数的函数名是运算符,而非我们平时所看到的和所写的一样。运算符有些可重载有些不可重载:

 

posted @ 2019-09-30 10:14  千浦千钰  阅读(875)  评论(0编辑  收藏  举报