|
程序是这样的:
#include<iostream>
#include<iomanip>
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& h);
};
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 % 4==0 && year % 100 )|| year % 400==0;
}
ostream& operator<<(ostream& o, const Date& h)
{
o<<setfill('0')<<setw(4)<<h.year<<'-'<<setw(2)<<h.month<<'-'
<<setw(2)<<h.day<<'\n'<<setfill(' ');
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;
}
错误是:
--------------------Configuration: sadf - Win32 Debug--------------------
Compiling...
sadf.cpp
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(32) : error C2248: 'year' : cannot access private member declared in class 'Date'
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(10) : see declaration of 'year'
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(32) : error C2248: 'month' : cannot access private member declared in class 'Date'
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(10) : see declaration of 'month'
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(33) : error C2248: 'day' : cannot access private member declared in class 'Date'
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(10) : see declaration of 'day'
F:\学习资料\编程\vc++\cpp文件\sadf.cpp(42) : error C2593: 'operator <<' is ambiguous
Error executing cl.exe.
sadf.obj - 4 error(s), 0 warning(s)
搞不明白,为什么说不能访类里的私有变量,明明可以的,这怎么解释啊? |
|