注册 登录
编程论坛 C++教室

[求助]输出流重载问题?

bill8888 发布于 2007-04-29 23:37, 1282 次点击

程序是这样的:
#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)


搞不明白,为什么说不能访类里的私有变量,明明可以的,这怎么解释啊?


[此贴子已经被作者于2007-4-29 23:38:03编辑过]

7 回复
#2
aipb20072007-04-30 00:24
https://bbs.bc-cn.net/viewthread.php?tid=133743&extra=&page=10#112525


看看这个,我想你遇到了一样的问题

编译器问题,换个gcc试试!
#3
bill88882007-04-30 00:35

我在DEV C++里运行能够通过
真不知道VC++是怎么回事啊
居然友元函数不能访问类里的私有变量,有违标准C++的规定嘛

#4
virtual_man2007-05-13 17:21

二楼楼主无限循环在他给出的连接中有相关解决问题的方法.我对这个问题也想了是不是vc++6的一个bug?我觉得应该不是吧,在DEV C++能通过编译在vc++不能通过不能代表有bug吧,这得取决于编译器怎么设计的问题,我的专业不搞编译器,所以我声明我不专业.是这样的,我认为,在你的类中要重载插入和提取符,但在你类的定义中根本就没有该重载函数的声明,所以必须先声明,叫前向声明.而在做了重载函数的前向声明后,由于提取符重载函数用到该类,所以在重载函数的声明之前也还要类的声明.这一系列的前向声明是符合编译器的先声明后使用的原则的.所以这个只是编译器怎么设计的问题,应该并不是个bug.

#5
yuyunliuhen2007-05-13 17:30
DEV的内核是GC++,它更加支持最新标准的C++,我愿意相信GC,虽然偶也用VC
#6
raulxxyuer2007-05-13 17:51
#7
游乐园2007-05-13 18:49
老问题 给VC++ 打上sp6 就可以了

要不就做提前声明也能解决

...
using namespace std;

class Date;
ostream& operator<<(ostream& o, const Date& h);

class Date {
...
#8
ningkli2008-11-14 14:11
可是为什么在c++里。用<iostream.h>代替<iostream>和using namespace std;却可以通过调试呢?
1