C++ 运算符重载
基本模式
[返回值类型] operator [需要重载的符号](参数1,参数2,..)
1.作为成员函数重载
// class
public:
BigInt operator+(const BigInt &num2);
//
BigInt BigInt::operator+(const BigInt &num2) {
BigInt ans;
//code here
return ans;
}
- 作为普通函数重载
当作为普通函数重载且需要访问类的私有成员时,需要把该函数制定为类的友元函数。
//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; //加完再用
}