zoukankan      html  css  js  c++  java
  • 类型转换 运算符重载

    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;  
    }  
  • 相关阅读:
    tuple-1
    禅语-1
    综述的写作技巧-1
    皆大欢喜组合
    类和对象-3
    双棍练习
    CodeBlocks开发环境使用-1
    类和对象-2
    类和对象-1
    13-归并排序-分治策略应用于排序
  • 原文地址:https://www.cnblogs.com/renyuan/p/6555172.html
Copyright © 2011-2022 走看看