类型转换 运算符重载

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

 
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;  
}  
相关文章
相关标签/搜索