一:重载目的
为了对对象进行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。
基于此,这种重载非常不人性化,与人们习惯出入太大,建议不宜使用。