头图

类类型是否能够转为普通类型?

类型转换函数

C++类中可以定义类型转换函数

类型转换函数用于将类对象转换为其他类型

#include <iostream>

#include <string>



using namespace std;



class Test

{

   int mvalue;

   public:

   Test (int i = 0)

   {

    mvalue = i;

   }

   int value_a()

   {

    return mvalue;

   }

   operator int()

   {

      return mvalue;

   }



};

int main()

{   

    Test t(100);

    int i =  t; 
    //int i = t.operator int();
    cout << "t.value_a="<<t.value_a()<<endl;
    cout << "i ="<<i<<endl;
    return 0;

}

输出:

t.value_a=100
i =100

例:

#include <iostream>

#include <string>



using namespace std;

class Test;
class Value
{
    public:
    Value()
    {
    
    }
   explicit Value(Test& t)
    {}
};

class Test

{

   int mvalue;

   public:

   Test (int i = 0)

   {

    mvalue = i;

   }

   int value_a()

   {

    return mvalue;

   }


  operator Value()
   {
    Value ret;
    return ret;
   }



};

int main()

{   

    Test t(100);
    Value v = t;

   // int i =  t; 
    //Value v =t.operator Value();
    //cout << "t.value_a="<<t.value_a()<<endl;
   // cout << "i ="<<i<<endl;
    return 0;

}

类型转换函数

无法抑制隐式的类型转换函数调用

类型转换函数可能与转换构造函数冲突

工程中以Type to Type的公有成员代替类型转换函数

小结:

C++类中可以定义类型转换函数

类型转换函数用于将类对象转换为其他类型

类型转换函数与转换构造函数具有同等的地位

工程中Type toType的公有成员代替类型转换函数


YingLi
6 声望4 粉丝

From zero to hero.