C++中如何重载<<

一:重载目的

为了对对象进行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。

基于此,这种重载非常不人性化,与人们习惯出入太大,建议不宜使用。



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值