Conversion Operators

《Moreeffective c++》Item M5中讲的比较清楚:

隐式类型转换运算符只是一个样子奇怪的成员函数:operator 关键字,其后跟一个类型符号。你不用定义函数的返回类型,因为返回类型就是这个函数的名字。例如为了允许Rational(有理数)类隐式地转换为double类型(在用有理数进行混合类型运算时,可能有用),你可以如此声明Rational类:

class Rational {

public:

...

operator double() const; // 转换Rational类成double类型

};

在下面这种情况下,这个函数会被自动调用:

Rational r(1, 2); // r 的值是1/2

double d = 0.5 * r; // 转换 r 到double, 然后做乘法


其它解释:

A conversion operator can be thought of as a user-defined typecasting operator; it converts its object to a different type in contexts that require that specific type. The conversion is done automatically.


Conversion operators differ from ordinary overloaded operators in two ways. First, a conversion operator has no return value (not even void). The return value is inferred from the operator's name. Secondly, a conversion operator takes no arguments. Conversion operators can convert their objects to any given type, fundamental and user-defined.


struct TPoint
{
    int x;
    int y;
};


void PrintPoint(TPoint& rstPoint)
{
    printf("(%d, %d)\n", rstPoint.x, rstPoint.y);
}


class CPoint
{
private:
    TPoint m_stPoint;


public:
    CPoint(int x, int y)
    {
        m_stPoint.x = x;
        m_stPoint.y = y;
    }


    operator TPoint&() 
    {
        return m_stPoint;
    }
};


struct TDateRep // legacy C code
{
    char day;
    char month;
    short year;
};


class CDate // object-oriented wrapper
{
private:
    TDateRep m_stDr;


public:
    // automatic conversion to DateRep
    operator TDateRep() const
    { 
        return m_stDr;
    }
};


// C-based communication API function
extern "C" int transmit_date(const TDateRep&);


int transmit_date(const TDateRep& rstDR)
{
    printf("transmit date info as a binary stream to a remote client");
    return 0;
}


int main(int argc, char* argv[])
{
    CPoint oPoint(1, 2);
    PrintPoint(oPoint);


    CDate oDate;
    //...use d


    // transmit date object as a binary stream to a remote client
    int i32Ret = transmit_date(oDate); // using legacy communication API


return 0;
}


转载于:https://my.oschina.net/u/3485339/blog/900437

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值