[置顶] c++,vc6.0,中友元函数,无法访问私有字段(private)的问题(problem),cannot access private member declared in class 'Date'

c++,vc6.0,中友元函数,无法访问私有字段(private)的问题(problem),cannot access private member declared in class 'Date'


代码如下:

#ifndef _DATE_H_
#define _DATE_H_
#include<iostream>
using namespace std;

class Date
{
public:
	Date();
	Date(int y,int m,int d);
	void printOn();
private:
	int _year;
	int _mounth;
	int _day;

friend const ostream& operator<<(ostream & out,Date d);
};
Date::Date():_year(0),_mounth(0),_day(0)
{}
Date::Date(int y,int m,int d):_year(y),_mounth(m),_day(d)
{
}
void Date::printOn()
{
 cout<<*this;
 
}

const ostream& operator<<(ostream & out,Date d)
{
	out<<d._year<<d._mounth<<d._day<<endl;
	return out;
}
#endif

错误提示如下图:



据说是VC的一个经典BUG。和namespace也有关.

只要含有using namespace std; 就会提示友员函数没有访问私有成员的权限。

解决方法:去掉using namespace std;换成更小的名字空间。

例如:
含有#include <string>就要加上using std::string
含有#include <fstream>就要加上using std::fstream
含有#include <iostream>就要加上using std::cin; using std::cout; using std::ostream; using std::istream; using std::endl; 等等,需要什么即可通过using声明什么.


更正后如下:

#ifndef _DATE_H_
#define _DATE_H_
#include<iostream>

//using namespace std;
using std::cin;
using std::endl; 
using std::cout;
using std::ostream;
using std::istream;
class Date
{
public:
	Date();
	Date(int y,int m,int d);
	void printOn();
private:
	int _year;
	int _mounth;
	int _day;

friend const ostream& operator<<(ostream & out,Date d);
};
Date::Date():_year(0),_mounth(0),_day(0)
{}
Date::Date(int y,int m,int d):_year(y),_mounth(m),_day(d)
{
}
void Date::printOn()
{
 cout<<*this;
 
} 
const ostream& operator<<(ostream & out,Date d)
{
	out<<d._year<<d._mounth<<d._day<<endl;
	return out;
}
#endif

 

或者更改如下:

#include<iostream.h>



posted @ 2013-08-02 16:13  shouqiang Wei  阅读(449)  评论(0编辑  收藏  举报