1.类类型是否可以转换为普通类型?
不可以…
2.类型转换函数
c++类中定义类型转换函数
类型转换函数用于将类对象转换为其它类型
语法规则
operator Type ()
{
Type ret;
//….
return ret
}
#include <iostream>#include <string>using namespace std;class Test{int mvalue;public:Test(){mvalue = 0;}Test(int i){mvalue = i;}int value(){return mvalue;}operator int(){int ret = mvalue;return ret;}};int main(){Test t(100);int i = t; //==t.operator int()cout << "t.value() = " << t.value() << endl;cout << "i = " << i << endl;return 0;}
类型转换函数与转换构造函数类似!!!
类型转换函数:
—-与转换构造函数具有同等的地位
—-使得编译器有能力将对象转化为其它类型
—-编译器能够隐式的使用类型转换函数
这里是一个ppt的内容
类型转换函数
ID.T”
www.dt4sW.com
编译器会尽力尝试让源码通过编译
Test
t(1):
“t这个对象为Test类型,怎么可能用于
int
七i
初始化int类型的变量呢!现在就报错吗?
不急,我看看有没有类型转换函数!Ok,
发现Test类中定义了operatorint0,可
以进行转换.
g2014D.T.SoftwareCorporation.
ID.T.SOFTWARE
http://shop.dt4sw.com
AIlnightsresered.
#include <iostream>#include <string>using namespace std;#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(){return mValue;}operator Value(){Value ret;cout << "operator Value()" << endl;return ret;}};int main(){Test t(100);// Value i = t; //==t.operator Value()Value i = t; //Value(t)//两个都存在的时候,编译器不知道怎么选择了,转换构造函数和类型转换函数是互逆的,//但是都存在时会产生冲突,所以用explicit,需要我们显示的转换才可以return 0;}
3.类类型之间的转换
无法抑制隐式的类型转换函数调用
类型转换函数可能与类型构造函数冲突
工程中以Type toType()的公有成员代替转换构造函数
#include <iostream>#include <string>using namespace std;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(){return mValue;}Value toValue(){Value ret;cout << "operator Value()" << endl;return ret;}};int main(){Test t(100);// Value i = t; //==t.operator Value()Value i = t.toValue(); //Value(t)//两个都存在的时候,编译器不知道怎么选择了,转换构造函数和类型转换函数是互逆的,//但是都存在时会产生冲突,所以用explicit,需要我们显示的转换才可以return 0;}
QT里面的例子:
#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;}
由此可见,qt中就是使用type totype来实现的类型转换
小结:
1.c++类中可以定义类型转换函数
2.类型转换函数用于将类对象转换为其它类型
3.类型转换函数与转换构造函数具有同等的地位
4.工程中以Type toType()公有成员函数来代替类型转换函数
