类型转换 运算符重载

C++中没有返回类型的函数有3个,构造函数、析构函数、类型转换函数。

 
operator const char *() const
如果是重载*的话,那应该写成:const char operator * () const而上面所写的那样,而且即使是这样写那也不正确的,
因为运算符重载中有几个运算符的返回值是有格式的(约定),如operator * 在重载时通常返回值是classType&或者const classType& 。
operator const char*() const是类型转换函数的定义,即该类型可以自动转换为const char*类型。至于最后一个const,
那个大家都知道是对类成员的限制(不允许更改对象的状态)。
 

类型转换运算符,只要你把XXX对象隐式或者显式转换为T对象时,它都会被自动调用。

#include<iostream>  
using namespace std;  
//类型转换运算符重载,只要你把XXX对象隐式或者显式转换为T对象时,它自动被调用  
  
  
template<class T>  
class Transfer  
{  
public:  
    Transfer(int arg):i(arg){}  
    operator T() const  
    {  
        return i;  
    }  
private:  
    int i;  
};  
  
int main()  
{  
    Transfer<double> t(3);  
    //double d =static_cast<double>(t);//显示转换  
    double d = t;//隐式转换  
    cout<<d;  
    getchar();  
    return 0;  
}  

 

posted @ 2017-03-15 17:03  任智康  阅读(2576)  评论(0编辑  收藏  举报