运算符重载之转换运算符
2016-04-11 10:33
351 查看
我们知道c++中,cout<<3、cout<<"hello"是没有问题的,但是若你声明了一个类Fish,想输出类的相关信息,使用 cout<<Fish是无法正确被识别的。当然你可以申明一个类成员函数print(),调用Fish.print(),但是我们可以重载转换运算符,使得输出更方便
要使cout能够正确输出你的对象,你只需要添加一个返回const char* 的运算符:
operate const char*() { \\operate implemetation that return a char* }
下面看一个完整的例子:
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> #include<string> #include<sstream> using namespace std; class student { private: int age; string name; string telephone; string student_Instring; public: student(int a,string n,string t):age(a),name(n),telephone(t){}; operator const char*() { ostringstream formattestudengt; formattestudengt<<name<<" is:"<<age<<" years old,\ \n and his telephone number is: "<<telephone<<endl; student_Instring=formattestudengt.str(); return student_Instring.c_str(); } }; int _tmain(int argc, _TCHAR* argv[]) { student Tom(30,"Tom Smith","13567879001"); cout<<Tom; return 0; }
运行结果:
ostringstream是C++的一个字符集操作模板类,定义在sstream.h头文件中。ostringstream类通常用于执行C风格的串流的输出操作,格式化字符串,避免申请大量的缓冲区,替代sprintf。详情参见博客
当然还可以编写其他云算符,如果你想对某个对象用整数表示,可以编写如下转换运算符。
operate int() { \\your conversion code here }
这样你的对象就可当整数用,如int x=class(实例)。
相关文章推荐
- rundeck Web页面配置node节点
- delphi socket客户端连接服务端时的错误
- 卸载Visual Studio Professional 2013
- Ping服务
- Oracle 10g RAC修改IP/VIP地址示例
- shell具体执行过程及自主实现shell解释器
- 安装配置gerrit
- sql小计合计
- 动态规划之0-1背包问题
- linux撰写策略路由
- Matlab与C/C++混合编程接口应用总结
- 3月国内电脑分辨率十强:1366*768亚军 占比破10%
- 使用jsoup完成模拟登陆
- 写给步入网络门槛中入门级别工程师中相关Vlan、trunk、hybrid的理解
- leetcode 237. Delete Node in a Linked List
- 字符串整理 1
- python 新手入门学习(一)
- [DevExpress]控件之GridLookupedit的运用
- linux配置网络参数
- 有关phpmailer的详细介绍及使用方法