C++ 运算符重载

C++ 运算符重载

基本模式

[返回值类型] operator [需要重载的符号](参数1,参数2,..)

1.作为成员函数重载

// class
public:
    BigInt operator+(const BigInt &num2);
//

BigInt BigInt::operator+(const BigInt &num2) {
    BigInt ans;
    //code here
    return ans;
}
  1. 作为普通函数重载

当作为普通函数重载且需要访问类的私有成员时,需要把该函数制定为类的友元函数。

//class
public:
    friend istream &operator>>(istream &is, BigInt &num);

    friend ostream &operator<<(ostream &os, const BigInt &num);
//
istream &operator>>(istream &is, BigInt &num) {
    //code here
    return is;
}

ostream &operator<<(ostream &os, const BigInt &num) {
    //code here
    return os;
}

一些特殊运算符的重载

流输入输出符

当重载 << >> 时,必须要以普通函数的形式重载

:因为你没法修改ostream ,istream 这些类

重载时,返回类型为ostream的引用

:为了实现连续输入 cin>>a>>b

自加自减运算符

主要是注意前置和后置的区别

后置

// in class
const BigInt operator++(int);
//
const BigInt BigInt::operator++(int) {
    BigInt temp = *this;
    *this = *this + BigInt(1);
    return temp;    //先用再加
}

前置

// in class
BigInt &operator++();
//
BigInt &BigInt::operator++() {
    *this = *this + BigInt(1);
    return *this;   //加完再用
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值