12th Jul 2007

奇特的运算符重载

一直以为 C++ 的运算符重载功能只限于 +, -, *, /, 这些. 今日看某书后才发现其范围远远不止.

考虑下面的代码

template <class Comparable>
class Pointer
{
    public:
        explicit Pointer(Comparable *rhs =NULL)
            :pointee( rhs ){}
        bool operator<(const Pointer & rhs ) const
        { return *pointee < *rhs.pointee; }
        operator Comparable * () const
        { return pointee; }
        Comparable * get () const
        { return pointee; }
 
    private:
        Comparable *pointee;
};

留意第九行, 没有返回类型, 很奇怪. 后来问老狼才知道原来这是运算符 (Comparable *)Pointer 的重载, 也就是平常所说的强制类型转换. 奇特的语法…

Leave a Reply