c++类型转换函数
来源:互联网 发布:尔雅网络课官网 编辑:程序博客网 时间:2024/06/10 05:28
类型转换函数的一般形式为:
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
0 0
- C类型转换函数
- C++static_cast类型转换函数
- C语言的常用类型转换函数
- C语言各种数值类型转换函数
- C语言各种数值类型转换函数
- C语言中的函数指针类型转换
- C语言常用数值类型转换函数
- C/C++中诸多类型转换函数
- C语言类型之间转换函数
- 【c/c++】类型转换函数(类型转换运算符重载函数)
- <C/C++> 类型转换
- C/C++:类型转换
- c#.net函数和方法集(各种值类型转换)
- 《more effective c++》Item M5:谨慎定义类型转换函数
- C++中Operator类型强制转换成员函数
- C++中Operator类型强制转换成员函数
- C++中Operator类型强制转换成员函数
- 函数调用中的类型转换 c提升规则
- Count Primes
- 5.17
- SQL Server数据库开发的21条军规
- #第47天#健身#
- MOOC Linux内核之旅小结
- c++类型转换函数
- L版本修改默认静态壁纸wallpaper
- 1011. A+B和C
- 约瑟夫问题的PHP实现——猴子选大王的问题
- 黑马程序员——异常的概述和分类
- POJ3259----Wormholes(最短路)
- EXTJS5+MVC(1)运行环境以及结构
- 命令行下修改DEP
- linux下svn常用指令