求解释 代码
#include<iostream>
#include<sstream>
#include<iomanip>
using std::cout;
using std::cin;
using std::endl;
using std::ostream;
using std::istream;
//using namespace std;
class Date
{
int year,month,day;
public:
Date(int y=2000,int m=1,int d=1);
Date(const string& s);
bool isleapyear()const;
friend ostream& operator<<(ostream& o,const Date& d);
};
Date::Date(const string& s)
{
year=atoi(s.substr(0,4).c_str());
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(8,2).c_str());
}
Date::Date(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
bool Date::isleapyear()const
{
return (year%400==0) || (year%100!=0 && year%4==0);
}
ostream& operator<<(ostream& o,const Date& d)
{
o<<setfill('0')<<setw(4)<<d.year<<setw(2)<<d.month<<setw(2)<<d.day<<setfill(' ')<<endl;
}
int main()
{
Date c("2005-12-28");
Date d(2003,12,6);
Date e(2002);
Date f(2002,12);
Date g;
cout<<c<<d<<e<<f<<g;
}
编译通不过,我照着《c++程序设计教程》敲的。自己也百度了一些,没找着。怎么改正。新手求教
[解决办法]
ostream& operator<<(ostream& o,const Date& d)
{
o<<setfill('0')<<setw(4)<<d.year<<setw(2)<<d.month<<setw(2)<<d.day<<setfill(' ')<<endl;
return o;
}
重载<<函数必须有相应流的返回值
[解决办法]
重载函数只不过是增加了特殊调用方式的普通函数,遵循普通函数的要遵循的规则。
ostream& operator<<(ostream& o,const Date& d)
表明他返回了ostream的引用,但是LZ没有。
[解决办法]
#include<iostream>
#include<sstream>
#include<string>
#include<iomanip>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::setfill;
using std::setw;
class Date
{
int year,month,day;
public:
Date(int y=2000,int m=1,int d=1);
Date(const string& s);
bool isleapyear()const;
friend std::ostream& operator<<(std::ostream& o,const Date& d);
};
Date::Date(const string& s)
{
year=atoi(s.substr(0,4).c_str());
month=atoi(s.substr(5,2).c_str());
day=atoi(s.substr(8,2).c_str());
}
Date::Date(int y,int m,int d)
{
year=y;
month=m;
day=d;
}
bool Date::isleapyear()const
{
return (year%400==0) || (year%100!=0 && year%4==0);
}
std::ostream& operator<<(std::ostream& o,const Date& d)
{
o<<setfill('0')<<setw(4)<<d.year<<setw(2)<<d.month<<setw(2)<<d.day<<setfill(' ')<<endl;
return o;
}
int main()
{
Date c("2005-12-28");
Date d(2003,12,6);
Date e(2002);
Date f(2002,12);
Date g;
cout<<c<<d<<e<<f<<g;
return 0;
}
改成这样就没问题了。。。如果不是特别必要,不要用using namespace std;而是看你需要用到啥,比如你需要用到 cout,你就用using std::cout;