c++操作符重载
- = [] () -> 操作符必须为类成员函数
- 复合赋值操作符(+= -= *= /=)通常定义为类的成员函数
- 自增(++)、自减(–)和解引用(*),通常定义为类的成员函数
- 算数操作符、相等操作符、关系操作符和位操作符,最好定义为普通非成员函数
定义为非成员函数
输出操作符
ostream&
operator << (ostream& os, const ClassType &object){
os << //.....
return os;
}
输入操作符
输入操作符必须处理可能出现的错误和文件结束,而输出运算符不需要
istream&
operator >>(istream& in, ClassType &s){
in >> s;
if(in){ //成功
//.....
}
else{ //失败
//.....
}
return in;
}
算数操作符
Sales_item
operator +(const Sales_item& lhs, const Sales_item& rhs){
Sales_item ret(lhs); // 拷贝构造
ret += rhs; // += 操作
return ret;
}
注意,返回一个右值,而不是一个引用
相等运算符及关系操作符
bool operator==(const Sales_item& lhs, const Sales_item& rhs){
return //比较
}
bool operator!=(const Sales_item& lhs, const Sales_item& rhs){
return !(lhs==rhs);
}
bool operator<(const ClassType &lhs, const ClassType &rhs){
return //比较
}
bool operator<=(const ClassType &lhs, const ClassType &rhs){
return lhs<rhs || lhs==rhs;
}
定义为成员函数
复合赋值操作符
ClassType& ClassType::operator +=(ClassType &rhs){
// ...
return *this
}
自增自减操作符
前自增(++ClassType)
ClassType& ClassType::operator++(){
/*
* 操作
*/
return *this;
}
后自增(ClassType++)
ClassType ClassType::operator++(int){
ClassType ret(*this);
++*this; //使用前自增操作
return ret;
}
- 后缀式操作符接受额外的int型参数来区分
- 为了与内置操作符一致,后缀操作符返回旧值,且为值返回
下标操作符
class Foo
{
public:
int &operator[](const size_t);
const int &operator[] (const size_t) const;
private:
std::vector<int> data;
};
int& Foo::operator[](const size_t index){
return data[index];
}
const int& Foo::operator[](const size_t index) const{
return data[index];
}
类定义下标操作符时,一般定义两个版本:一个为非const成员并返回引用,一个为const成员并返回const引用。