自增运算符++ ,自减运算符–有前置/后置之分,为了区分所重载的是前置运算符还是后置运算符,C++规定:
前置运算符作为一元运算符重载
T & operator ++ ( )
T & operator -- ( )
T & operator ++ ( T& )
T & operatot -- ( T& )
后置运算符作为二元运算符重载,多写一个没用的参数
T & operator ++ ( int n)
T & operator -- ( int n)
T & operator ++ ( T & , int n)
T & operator -- ( T & , int n)
但是在没有后置运算符重载而有前置运算符重载的情况下,在VS中,obj++也调用前置重载,在dev中,则obj++编译出错
class CDemo{
int n;
public:
CDemo ( int i= 0 ) : n ( i) { }
CDemo operator++ ( int ) ;
CDemo & operator++ ( ) ;
friend CDemo operator-- ( CDemo & , int ) ;
friend CDemo & operator-- ( CDemo & ) ;
friend ostream & operator<< ( ostream & os, const CDemo & d) ;
} ;
ostream & operator << ( ostream & os, const CDemo & d) {
os << d. n;
return os;
}
CDemo CDemo: : operator++ ( int ) {
CDemo tmp ( * this) ;
n++ ;
return tmp;
}
CDemo & CDemo: : operator++ ( ) {
n++ ;
return * this;
}
CDemo operator-- ( CDemo & d, int ) {
CDemo tmp ( d) ;
d. n-- ;
return tmp;
}
CDemo & operator-- ( CDemo & d) {
d. n-- ;
return d;
}
int main ( ) {
CDemo d ( 5 ) ;
cout << ( d++ ) << ',' ;
cout << d << ',' ;
cout << ( ++ d) << ',' ;
cout << d << ',' ;
cout << endl;
cout << ( d-- ) << ',' ;
cout << d << ',' ;
cout << ( -- d) << ',' ;
cout << d << ',' ;
cout << endl;
return 0 ;
}
写<<运算符重载的时候发现一个问题,就是第二个参数对CDemo 的引用必须是常引用,不加const编译不过,使用的是dev,有点纳闷
ostream & operator << ( ostream & os, CDemo & d) {
os << d. n;
return os;
}