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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值