复习--重载

## 什么是重载

C++重载分为:函数重载、操作符重载

函数重载:函数名相同参数不同

操作符重载:对一些常规操作进行重载,这样方便对象之间的操作。

反例:返回值不同,不能作为函数重载的差异

 

## 重载的用法

#include <iostream>
#include <string>

using namespace std;

class OverloadDemo
{
public:
    void Print(int i);
    void Print(string str);    
};


void OverloadDemo::Print(int i) 
{
    cout << "int: " << i << endl;
}

void OverloadDemo::Print(string str)
{
     cout << "string: " << str << endl;
}

class Ball
{
public:
    void SetRadius(double radius);
    double GetVolume();
    Ball& operator+(const Ball &ball)
    {
        this->radius = this->radius + ball.radius;
        return *this;
    }
private:
    double radius;
};

void Ball::SetRadius(double radius)
{
    this->radius = radius;
}

double Ball::GetVolume()
{
    return 3.1415926 * (this->radius * this->radius);
}

int main()
{
    OverloadDemo demo;
    demo.Print(3);
    demo.Print("pangyemeng");

    Ball ball_1, ball_2, ball_3;
    ball_1.SetRadius(2);
    double volume1 = ball_1.GetVolume();
    cout << "ball1 volume1: " << volume1 << endl;

    ball_2.SetRadius(3);
    double volume2 = ball_2.GetVolume();
    cout << "ball2 volume2: " << volume2 << endl;
    cout << "volume1 + volume2 = " << volume1 + volume2 << endl;
    
    ball_3 = ball_1 + ball_2;
    double volume3 = ball_3.GetVolume();
    cout << "ball3 volume3: " << volume3 << endl;

    return 0;
}


[root@VM-0-2-centos cpp]# g++ -o overload_demo overload_demo.cpp 
[root@VM-0-2-centos cpp]# ./overload_demo 
int: 3
string: pangyemeng
ball1 volume1: 12.5664
ball2 volume2: 28.2743
volume1 + volume2 = 40.8407
ball3 volume3: 78.5398

## 重载的使用场景

从开发的角度而言,运算符重载的存在是为了提高开发效率,增加代码的可复用性,很多时候反而是简化了问题。C++强大的原因之一是支持泛型编程。泛型编程使得算法可以独立于数据类型存在。自定义的数据类型通过操作符重载具有了和内建类型同样的使用接口,然后C++的模板加持下,你的算法可以利用这种接口一致性,实现泛化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值