浅谈操作符重载

5 篇文章 0 订阅

目录

 

操作符重载函数是什么

操作符重载函数,是编译时多态的一种体现。

操作符重载函数的实现又分为:类的成员函数,非类的成员函数。

举例 ==重载函数


  • 操作符重载函数是什么

operator 是C++的一个关键字,它和运算符(如=)一起使用,表示一个运算符重载函数,在理解时可将operator和运算符(如operator=)视为一个函数名。

使用operator重载运算符,是C++扩展运算符功能的方法。使用operator扩展运算符功能的原因如下:

使重载后的运算符的使用方法与重载前一致

扩展运算符的功能只能通过函数的方式实现(实际上,C++中各种“功能”都是由函数实现的)


  • 操作符重载函数,是编译时多态的一种体现。


  • 操作符重载函数的实现又分为:类的成员函数,非类的成员函数。


  • 举例 ==重载函数

作为类的成员函数:

bool operator==(const person& ps)
{
    if (this->age == ps.age)
    {
        return true;
    }
    return false;
}
//示例代码(operator_test2.cpp)如下:

#include <iostream>
 
using namespace std;
 
class person
{
private:
    int age;
public:
    person(int nAge)
    {
        this->age = nAge;
    }
 
    bool operator==(const person& ps)
    {
        if (this->age == ps.age)
        {
            return true;
        }
        return false;
    }
};
 
int main()
{
    person p1(10);
    person p2(10);
    
    if (p1 == p2)
    {
        cout << "p1 is equal with p2." << endl;
 
    }
    else
    {
        cout << "p1 is not equal with p2." << endl;
    }
    
    return 0;
}

作为非类的成员函数:

#include <iostream>
 
using namespace std;
 
class person
{
public:
    int age;
};
 
// 左操作数的类型必须被显式指定
// 此处指定的类型为person类
bool operator==(person const& p1 ,person const& p2)
{
    if (p1.age == p2.age)
    {
        return true;
    }
    else
    {
        return false;
    }
}
 
int main()
{
    person p1;
    person p2;
    p1.age = 18;
    p2.age = 18;
 
    if (p1 == p2)
    {
        cout << "p1 is equal with p2." << endl;
    }
    else
    {
        cout << "p1 is NOT equal with p2." << endl;
    }
 
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值