C++ 重载(包括有重载函数和重载运算符)

一、函数重载

函数重载是一种特殊情况,C++允许在同一作用域中声明几个类似的同名函数,这些同名函数的形参列表(参数个数,类型,顺序)必须不同。

注意:c语言不允许函数重载

下面同名set,但是不同的形参列表,执行不同的任务。

#include "iostream"
using namespace std;
class Person{
public:
    void set(int num,string name){
        this->number=num;
        this->name=name;
        cout<<"name: "<< this->name;
        cout<<"  number: "<< this->number<<endl;
    }
    void set(string name){
        this->name=name;
        cout<<"name: "<< this->name<<endl;
    }
private:
    string name;
    int number;

};

int main(){
    Person person;
    person.set(133,"antonio");//name: antonio  number: 133
    person.set("steve");//name: steve
    return 0;
}

二、运算符重载

运算符重载是让运算符在不同情况执行不同功能。

重载运算符格式

返回值类型 operator 运算符名称 (形参表列){
    //TODO:
}

具体示例如下:

#include "iostream"
using namespace std;
class Complex{
public:
    //默认构造函数
    Complex(){
        this->real=0.0;
        this->imaginary=0.0;
    }
    Complex(float real,float imaginary){
        this->real=real;
        this->imaginary=imaginary;
    }
    void setReal(float real){
        this->real=real;
    }
    void setImaginary(float imaginary){
        this->imaginary=imaginary;
    }
    void show(){
        cout<<"imaginary number is :"<<this->real<<"+"<<this->imaginary<<"i"<<endl;
    }
    //重载运算符+
    Complex operator +(const Complex &a){
        Complex B;
        B.real=this->real+a.real;
        B.imaginary=this->imaginary+a.imaginary;
        return B;
    }
    //const修饰形参表明是一个输入参数,在函数内部不可以改变其值
    friend Complex operator -(const Complex &a,const Complex &b);
private:
    float real;
    float imaginary;

};
//重载-为全局函数,故而需要在类中设置友元
Complex operator -(const Complex &a,const Complex &b){
    Complex B;
    B.real=a.real-b.real;
    B.imaginary=a.imaginary-b.imaginary;
    return B;
}
int main(){
    Complex complex1(10.5,10.7);
    Complex complex2(10.2,10.5);
    Complex complex3=complex1+complex2;
    Complex complex4=complex1-complex2;
    complex1.show();//imaginary number is :10.3+10.4i
    complex2.show();//imaginary number is :10.5+10.6i
    complex3.show();//imaginary number is :20.8+21i
    complex4.show();//imaginary number is :0.3+0.2i
    return 0;
}

原文链接: https://www.cnblogs.com/AntonioSu/p/12283691.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/192865

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午6:11
下一篇 2023年2月12日 下午6:11

相关推荐