类型转换函数的一般形式为:
operator 类型名( )
{
实现转换的语句
}
在函数名前面不能指定函数类型,函数没有参数。其返回值的类型是由函数名中指定的类型名来确定的。类型转换函数只能作为成员函数,因为转换的主体是本类的对象。不能作为友元函数或普通函数。
输出结果:
operator 类型名( )
{
实现转换的语句
}
在函数名前面不能指定函数类型,函数没有参数。其返回值的类型是由函数名中指定的类型名来确定的。类型转换函数只能作为成员函数,因为转换的主体是本类的对象。不能作为友元函数或普通函数。
从函数形式可以看到,它与运算符重载函数相似,都是用关键字operator开头,只是被重载的是类型名。
1. 转换函数必须是成员函数,不能指定返回类型,并且形参表必须为空;返回值是隐含的,返回值是与转换的类型相同的,即为上面原型中的T2;
2. T2表示内置类型名(built-in type)、类类型名(class type)或由类型别名(typedef)定义的名字;对任何可作为函数返回类型的类型(除了 void 之外)都可以定义转换函数,一般而言,不允许转换为数组或函数类型,转换为指针类型(数据和函数指针)以及引用类型是可以的;
3. 转换函数一般不应该改变被转换的对象,因此转换操作符通常应定义为 const 成员;
4. 支持继承,可以为虚函数;
5. 只要存在转换,编译器将在可以使用内置转换的地方自动调用它;
函数原型:
T1::operator T2() const //T1的成员函数,"(T2)a"类型转换
实例代码:
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
class CString
{
public:
CString();
CString(string& str);
CString(const string& str);
virtual ~CString();
operator string()
{
cout << "call function convert to string\n";
return m_string;
}
operator int()
{
cout << "call function convert to int\n";
return atoi(m_string.c_str());
}
friend ostream& operator<<(ostream& os, const CString& str);
public:
string m_string;
};
CString::CString()
{}
CString::CString(string& str):m_string(str){}
CString::CString(const string& str)
{
m_string = str;
}
CString::~CString(){}
ostream& operator<<(ostream& os, const CString& str)
{
os << str.m_string;
return os;
}
int main(int argc, char *argv[])
{
CString str("ssssss");
cout << str<<endl;
string str2 = str;
cout << str2 <<endl;
string str3 = "5";
CString str4 = str3;
int t = str4;
cout << t << endl;
return 0;
}
输出结果:
ssssss
call function convert to string
ssssss
call function convert to int
5