istream 运算符重载 C++ [英] istream operator overloading c++

查看:104
本文介绍了istream 运算符重载 C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个简单的 istream 运算符重载,但是由于某种原因,一旦进入这个函数,程序就会进入无限循环.请帮忙!

i'm trying to do a simple istream operator overloading, but for some reason, once entering this function, the program enters an infinite loop. please help!

我的代码:

#include <iostream>
#include <string>
using namespace std;

 class date{

int m_day,m_month,m_year;

public:

date(int day=1,int month=1,int year=2000){    //constructor
    if (day>0 && day<32 && month>0 && month<13){
        m_day =day;
        m_month=month;
        m_year=year;
    }
}


friend ostream& operator<< (ostream& out, const date& d);
friend istream& operator>> (istream& in, const date& d);
};


istream& operator>> (istream& stream, const date& d){              //overload >>
stream >> d.m_day;
return stream;

}

void main(){  

date date1;

cin>>date1;                   //check istream

getchar();
}

推荐答案

这段代码在我看来是错误的,因为您正在尝试修改 const 对象 (d).

This code seems wrong to me, since you are trying to modify a const object (d).

istream& operator>> (istream& stream, const date& d){              //overload >>
    stream >> d.m_day;
    return stream;    
}

这篇关于istream 运算符重载 C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆