【C++】重载运算符&重载函数

  • 重载: C++允许同一作用域某个函数/运算符指定多个定义, 其参数列表,定义实现不同
  • 重载决策: 调用一个重载函数/重载运算符时, 将所用参数类型与定义中的参数类型比较, 选择合适定义

函数重载

  • 同一作用域内可声明几个功能类似的同名函数, 其形参必须不同
class printData
{
    public:
        void print(int i){
            cout << i << endl;
        }
        void print(double f){
            cout << f << endl;
        }
        void print(char c[]){
            cout << c << endl;
        }
}

运算符重载

  • 重定义C++内置运算符, 可使用自定义类型的运算符
  • 重载运算符有一个返回类型和一个参数列表
#include<iostream>
using namespace std;
class Box
{
    int length;
    int width;
    int height;
    public:
        Box(int len, int wid, int hei)
        {
            length = len;
            width = wid;
            height = hei;
        }
        double getVolume(void)
        {
            return length * width * height;
        }
        Box operator+(const Box& b)
        {
            Box box(0,0,0);
            box.length = this->length + b.length;
            box.width = this->width + b.width;
            box.height = this->height + b.height;
            return box;
        }
};
int main()
{
    Box B1(10,20,30);Box B2(40,50,60);Box B3(0,0,0);
    B3 = B1 + B2;
    cout << B3.getVolume();
}

可重载/不可重载, 实例

猜你喜欢

转载自blog.csdn.net/weixin_46143152/article/details/126783296