C++ 运算符重载 operator xxx * ()

来源:互联网 发布:梦幻西游网络错误 编辑:程序博客网 时间:2024/05/29 04:55

今天看见一段code。 发现一个很好玩的用法. 可能我见识少吧。记录一下:

class Loop
{
public:
。。。。。。
    inline operator event_base * () const
    {
        return _base;
    };
}

乍一看,还真没看明白这个的用途。研究一下,这个函数很管用。这个函数会把这个class的指针转化为event_base指针。当然你的class里边要有event_base*的成员。

看下边的例子



class Vector
{
public:
    float x,y,z;



    Vector() : x(0), y(0), z(0){
    }

    Vectorfloat x, float y, float z ) : x(x), y(y), z(z){
    }

    operator float*(){
        return &x;
    }

    operator const float *(){
        return &x;
    }

我们就可以这么玩了

Vector x(123);
float* f = x;
assert(*f == 1);

怎么样,是不是很好玩  哈哈

0 0