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