zoukankan      html  css  js  c++  java
  • [置顶] 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>



  • 相关阅读:
    MVC应用程序与单选列表
    jQuery UI的datepicker()与变更格式
    MVC应用程序,动态创建单选列表(RadioButtonList)
    MVC应用程序中,怎样控制与复制相同的功能
    为PartialView传递一个参数
    Nginx高并发性能优化
    Nginx上传和超时时间限制 (php上传限制)
    Nginx反向代理Tomcat访问时浏览器加载失败,出现 ERR_CONTENT_LENGTH_MISMATCH 问题
    Nginx域名访问的白名单配置
    日常运维中的一键安装或启停脚本
  • 原文地址:https://www.cnblogs.com/wsq724439564/p/3258153.html
Copyright © 2011-2022 走看看