第42课

1. 类型转换函数

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

(2)类型转换函数用于类对象转换为其它类型

(3)语法规则:

operator Type()   //重载类型运算符
{

    Type ret;

    //……

    return ret;

}

【编程实验】类型转换函数初探   42-1.cpp

#include <iostream>

 

using namespace std;

 

class Test
{

    int mValue;

public:

    Test(){mValue = 0;}

   

    //转换构造函数
    Test(int i = 0)
    {

        mValue = i;

    }

    //类型转换函数
    operator int()
    {

         return mValue;

    }


    int value()
    {

        return mValue;

    }

};


int main()
{

    Test t(100);

    int i = t; //t对象是Test类型,会调用转为int的类型转换函数

               //即隐式调用类型转换函数,等价于int i = t.operator int();   

   
    cout << "t.value() = "  << t.value() << endl; //100;

    cout << "i = " << i << endl; //100

    return 0;

}

运行结果: 

  

2. 类型转换函数意义

(1)类型转换函数转换构造函数具有同等的地位

(2)使用编译器有能力对象转化为其它类型

(3)编译器尽力尝试让源码通过编译

Test t(1);

int i = t; //t对象为Test类型,怎么可能用于初始化int类型的变量呢?现在就报

           //错吗?不急,编译器会看看有没有类型转换函数!Ok,发现Test类中定

           //opreator int(),可以进行转换。

(4)编译器能够隐式使用类型转换函数

【编程实验】类类型之间的转换   42-2.cpp

#include <iostream>

 

using namespace std;

 

//前置声明
class Test;

 

class Value
{

public:

    Value(){}

   

    //转换构造函数
    explicit Value(Test& t)
    {

       
    }

};

 

class Test
{

    int mValue;

public:

    Test(){mValue = 0;}

   

    //转换构造函数
    Test(int i = 0)
    {

        mValue = i;

    }

   

    //类型转换函数
    operator Value()
    {

        Value ret;

        cout << "operator Value()" << endl;

        return ret;

    }

   

    int value()
    {

        return mValue;

    }

};

 

int main()
{

    Test t(100);

    Value v = t; //如果Value类中的转换构造函数不加explicit,这会造成Test类的类型

                 //转换函数与Value类的转换构造函数的冲突。因为编译器看到这行时

                 //会出现两种理解1、Value v(t),调用的是Value类的转换构造函数

                 //也可以理解成Value v = t.operator Value();调用的是Test类的类

                 //型转换函数,出现了二义性。因此加上explicit后会阻止第1种可能

                 //最后,等价于第2种,所以结果会输出:"operator Value()"

                

    //Value v = static_cast<Value>(t);//相当于value v(t);                

   

    return 0;

}

运行结果:

  

3. 注意事项

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

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

(3)工程中以Type toType()公有成员代替类型转换函数,如toInt()、toString()等

【编程实验】类类型之间的转换  qt_test.cpp

#include <QDebug>
#include <QString>

int main()
{
    QString str = "";
    int i = 0;
    double d = 0;
    short s = 0;

    str = "-255";
    i = str.toInt();
    d = str.toDouble();
    s = str.toShort();

    qDebug() << "i = " << i << endl;
    qDebug() << "d = " << d << endl;
    qDebug() << "s = " << s << endl;

    return 0;
}

4. 小结

(1)C++可以定义类型转换函数

(2)类型转换函数用于类对象转换为其它类型

(3)类型转换函数转换构造函数具有同等的地位

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

原文地址:https://www.cnblogs.com/hoiday/p/10166514.html