栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

黑马程序员C++笔记

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

黑马程序员C++笔记

4.5运算符重载

运算符重载的概念:对已有运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型

4.5.1加号运算符重载

作用:实现两个自定义的数据类型相加的运算

对于内置的数据类型,编译器知道如何进行运算

int a=10;

int b=10;

int c=a+b;

class Person{

public:

int m_A;

int m_B;

}

Person p1:

p1.m_A=10;

p1.m_B=10;

Person p2:

p2.m_A=10;

p2.m_B=10;//实例化两个对象

Person p3=p1+p2;//让p1.m_A+p2.m_A

通过自己写成员函数,实现两个对象相加属性后返回的新对象

Person PersonAddPerson(Person &p)

{  

Person temp;

temp.m_A=this->m_A+p.m_A;

temp.m_B=this->m_B+p.m_B;

return temp;

}

编译器起了一个通用的名称

1).通过成员函数重载+号

Person operator+(Person &p)

{  

Person temp;

temp.m_A=this->m_A+p.m_A;

temp.m_B=this->m_B+p.m_B;

return temp;

}

operator+

应用:

Person p3=p1.operator+(p2);

简化为

Person p3=p1+p2;

2).通过全局函数重载+号

Person operator+ (Person &p1,Person &p2)

{

Person temp;

temp.m_A=p1.m_A+p2.m_A;

temp.m_B=p1.m_B+p2.m_B;

return temp;

}

Person p3=operator+(p1,p2);

可以简化为

Person p3=p1+p2;

上课代码:

总结:1.对于内置的数据类型的表达式的运算符是不可能改变的

2.不要滥用运算符重载(+写成-之类)

#include
using namespace std;
//加号运算符重载
class Person
{
public:

    //1.成员函数重载+号
    

    int m_A;
    int m_B;
};

//2.全局函数重载+号
Person operator+(Person& p1, Person& p2)
{
    Person temp;
    temp.m_A = p1.m_A + p2.m_A;
    temp.m_B = p1.m_B + p2.m_B;
    return temp;
}

//函数重载的版本:
Person operator+(Person& p1, int num)
{
    Person temp;
    temp.m_A = p1.m_A + num;
    temp.m_B = p1.m_B + num;
    return temp;
}
void test01()
{
    Person p1;
    p1.m_A = 10;
    p1.m_B = 10;
    Person p2;
    p2.m_A = 10;
    p2.m_B = 10;

    //成员函数重载本质调用:
    //Person p3 = p1.operator+(p2);
    //全局函数重载的本质调用:
    //Person p3=operator+(p1,p2);

    Person p3 = p1 + p2;//没重载函数时报错,报错原因是没有与这些操作数匹配的+运算符,操作数类型为:Person+Person

    //运算符重载也可以发生函数的重载
    Person p4 = p1 + 100;//报错,没有与这些操作符匹配的+运算符,操作类型为:Person+int

    cout << "p3.m_A=" << p3.m_A << endl;
    cout << "p3.m_B=" << p3.m_B << endl;

    cout << "p4.m_A=" << p4.m_A << endl;
    cout << "p4.m_B=" << p4.m_B << endl;
}

//2.全局函数重载+号
int main()
{
    test01();
    system("pause");
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1008616.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号