C++中如何重载<<
来源:互联网 发布:苹果最新软件 编辑:程序博客网 时间:2024/06/05 03:29
一:重载目的
为了对对象进行IO操作。
二:实现方法
1,成员函数中实现
2,普通函数中实现
#include <iostream>#include<sstream>#include<string>using namespace std;class Date{public: int day; int month; int year; string DateInString;public: Date(int inputDay,int inputMonth,int inputYear):day(inputDay),month(inputMonth),year(inputYear){} //prefix Date& operator ++() { ++day; return *this; } Date& operator --() { --day; return *this; } //postfix Date operator ++(int) { Date Copy(day,month,year); ++day; return Copy; } Date& operator --(int) { --day; return *this; } void display() { cout<<day<<" / "<<month<<" / "<<year<<endl; } operator <<(ostream& out) { cout<<this->day<<" / "<<this->month<<" / "<<this->year<<endl; cout<<"Aha, I am One!"<<endl; } operator const char*() { ostringstream format; format<<this->day<<" / "<<this->month<<" / "<<this->year<<endl; cout<<"Aha, I am Two!"<<endl; DateInString = format.str(); return DateInString.c_str(); }};Date& operator+(const Date& d1,const Date& d2){ Date tmp(10,4,2016); tmp.day = d1.day + d2.day; Date& d3 = tmp; return d3;}void operator <<(ostream& out,const Date& d1){ cout<<d1.day<<" / "<<d1.month<<" / "<<d1.year<<endl; cout<<"Aha, I am Three!"<<endl;}int main(){ Date* p1 = new Date(16,4,2016); Date* p2 = new Date(10,4,2016); (*p1)<<cout; cout<<(*p2); if(p1!=NULL && p2!=NULL) delete p1,p2; return 0;}
在上述代码中,我在类中重载了<<,在类外也重载了<<。
输出结果是什么呢?
******************************
16 / 4 / 2016
Aha, I am One!
10 / 4 / 2016
Aha, I am Three!
******************************
说明operator const char*()这个函数没有被调用,为什么呢?因为被全局函数void operator <<(ostream& out,const Date& d1)覆盖了。
如果我把全局函数注释掉,会怎样呢?
先看结果
******************************
16 / 4 / 2016
Aha, I am One!
Aha, I am Two!
10 / 4 / 2016
******************************
说明,(*p1)<<cout调用了operator const char*()这个函数。
再来说说:operator <<(ostream& out)
<<接受两个参数,左参数默认为(*this),右参数显示给出。所以只能是这种怪异的语句:(*p1)<<cout。
基于此,这种重载非常不人性化,与人们习惯出入太大,建议不宜使用。
0 0
- C++中如何重载<<
- 重载 方括号 中括号 [][] [C++]
- C中没有函数重载!
- c/c++中如何写结构体的 构造函数 和 重载运算符?
- 【C/C++】C++中函数重载原理
- 如何实现 C 的函数重载
- c语言如何实现函数重载
- [c++]如何取重载函数的地址
- [c#]Webservice中如何实现方法重载(overload)以及如何传送不能序列化的对象作参数
- 如何在WebService中重载方法
- 如何在WebService中重载方法
- 如何判断java中方法是否重载
- c#中webservice函数如何实现重载
- [C++]关于C++中继承、重载、掩盖
- [C++]关于C++中继承、重载、掩盖
- [C++]关于C++中继承、重载、掩盖
- 矩形类中运算符重载【C++】
- 矩形类中运算符重载【C++】
- kconfig 和 config.in 语法 翻译
- ZOJ 3922Candy with chocolate(几何)
- 人工智能\机器学习\统计学\数据挖掘之间有什么区别?
- Experimental Plugin User Guide
- CodeForces 639 A
- C++中如何重载<<
- 杭电1874-畅通工程续(SPFA算法)
- 产品学习梳理1-产品功能规划
- flask框架:Python 3.5下使用 flask_SqlAlchemy和mysql
- 关于IO流的那些事
- 旧键盘 (20) (c++/python)
- driver: Linux设备模型之input子系统详解
- 一个随时间不断变化的值确认其变化范围的方法
- 未能守到云开见日