目录
Overloaded operators must
operator
keyword as a prefix to name operator *(...)
+-*/%^&|~
const T operatorX(const T& l, const T& r) const;
! && || < <= == >= >
bool operatorX(const T& l, const T& r) const;
[]
T& T::operator[](int index)
class Integer{
public:
const Integer& operator++(); //prefix++
const Integer operator++(int); //postfix++
const Integer& operator--(); //prefix--
const Integer operator--(int); //postfix--
};
const Integer& Integer::operator++(){
*this += 1;
return *this;
}
//int argument not used so leave unnamed so won't get compiler warnings
//int参数未使用,因此保留未命名,因此不会收到编译器警告
const Integer Integer::operator++(int){
Integer old(*this);
++(*this);
return old;
}
class Integer{
public:
bool Integer::operator==( const Integer& rhs ) const;
bool Integer::operator!=( const Integer& rhs ) const;
bool Integer::operator< ( const Integer& rhs ) const;
bool Integer::operator> ( const Integer& rhs ) const;
bool Integer::operator>=( const Integer& rhs ) const;
bool Integer::operator<=( const Integer& rhs ) const;
};
bool Integer::operator==( const Integer& rhs ) const{
return i == rhs.i;
}
//implement lhs != rhs in terms of !(lhs == rhs)
bool Integer::operator!=( const Integer& rhs ) const{
return !(*this == rhs);
}
bool Integer::operator< ( const Integer& rhs ) const{
return i < rhs.i;
}
//implement lhs > rhs in terms of lhs < rhs
bool Integer::operator> ( const Integer& rhs ) const{
return rhs < *this;
}
//implement lsh <= rhs in terms of !(lhs < rhs)
bool Integer::operator<=( const Integer& rhs ) const{
return !(rhs < *this);
}
//implement lsh >= rhs in terms of !(lhs < rhs)
bool Integer::operator>=( const Integer& rhs ) const{
return !(*this < rhs);
}
从函数原型可知,6个关系运算符都由小于和等于演变而成,若要修改较为方便。
T& T::operator=(const T& rhs){
//check for self assignment
if(this != &rhs){
//perform assignment
}
return *this;
}
class One{
public:
One(){}
};
class Two{
public:
//Two(const One&) {}
explicit Two(const One&) {}
};
void f(Two) {}
int main()
{
One one;
//f(one); No auto conversion allowed
f(Two(one)); //OK -- user performs conversion
}
Reference:
原文:https://www.cnblogs.com/Mered1th/p/10887270.html