Overloaded operators

时间:2019-05-18 22:03:33   收藏:0   阅读:151

Overloaded operators

Restrictions

Member Functions

The prototypes of operators

operator ++ and --

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;
}

Relational operators

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个关系运算符都由小于和等于演变而成,若要修改较为方便。

operator []

operator =

T& T::operator=(const T& rhs){
    //check for self assignment
    if(this != &rhs){
        //perform assignment
    }
    return *this;
}

Value classes

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:

面向对象程序设计-C++

原文:https://www.cnblogs.com/Mered1th/p/10887270.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!