类类型是否能够类型转换为普通类型
可以,通过类型转换函数
类型转换函数:
(1)C++类中可以定义类型转换函数
(2)类型转换函数用于将类对象转换为其他类型
(3)语法规则:
operator Type ()
{
Type ret;
//......
return ret;
}
类型转换函数:
与转换构造函数具有同等地位
使得编译器有能力将对象转化为其他类型
编译器能够将隐式的使用类型转换函数
#include <iostream>
#include <string>
using namespace std;
class Test
{
int mvalue;
public:
Test(int i = 0)
{
mvalue = i;
}
int value()
{
return mvalue;
}
operator int()
{
return mvalue;
}
};
int main()
{
Test t(100);
int i = t; //编译器行为,t为Tes类型,先看看有没有类型转换函数,有可以进行转换 ==> int i = t.operator int ();
cout << "t.value() = " << t.value() << endl;
cout << "i = " << i << endl;
return 0;
}
类类型之间的相互转换?
类型构造转换函数:
(1)无法抑制隐式的类型转换函数调用
(2)类型构造函数可能与转换构造函数冲突
(3)工程中以Type to Type()的公有成员代替类型转换函数
#include <iostream>
#include <string>
using namespace std;
class Test;
class Values
{
public:
Values()
{
}
explicit Values(Test& t) //转换构造函数
{
}
};
class Test
{
int mvalue;
public:
Test(int i = 0)
{
mvalue = i;
}
int value()
{
return mvalue;
}
operator int()
{
return mvalue;
}
operator Values() //作用将Test类对象转换为Values对象
{
Values ret;
return ret;
}
/*Values toValues()
{
Values ret;
return ret;
}*/
};
int main()
{
Test t(100);
//Values v = t; // Values(t)
Values v = t;
//Values v = t.toValues(); // 工程中的用法
return 0;
}