VC6.0中友元函數無法訪問類私有成員的解決辦法

#include<iostream>

using namespace std;

class cylinder

{

    friend istream operator>>(istream& is,cylinder &cy);

public:    

    inline double square()

    {       return length*(width+height)*2+width*height*2;    }

    inline double volume()

    {      return length*width*height;      }

private:

    double length;

    double width;

    double height;

};

istream operator>>(istream is,cylinder &cy)

{

    cout<<"input length:"<<endl;

    is>>cy.length;

    cout<<"input width:"<<endl;

    is>>cy.width;

    cout<<"input height:"<<endl;

    is>>cy.height;

    return is;

}

int main()

{

    cylinder first;

    cin>>first;

    cout<<first.square()<<endl;

    cout<<first.volume()<<endl;

    return 0;

}

 

這些代碼在VC6.0中不能被編譯通過:提示不能訪問私有成員,沒有這個訪問權限 

改成這樣就可以了,代碼如下: 

 

#include<iostream>

using std::cin;

using std::endl; using std::cout;

using std::ostream;

using std::istream;

using std::ostream;

class cylinder

{

    friend istream operator>>(istream& is,cylinder &cy);

public:    

    inline double square()

    {       return length*(width+height)*2+width*height*2;    }

    inline double volume()

    {      return length*width*height;      }

private:

    double length;

    double width;

    double height;

};

istream operator>>(istream is,cylinder &cy)

{

    cout<<"input length:"<<endl;

    is>>cy.length;

    cout<<"input width:"<<endl;

    is>>cy.width;

    cout<<"input height:"<<endl;

    is>>cy.height;

    return is;

}

int main()

{

    cylinder first;

    cin>>first;

    cout<<first.square()<<endl;

    cout<<first.volume()<<endl;

    return 0;

}

 

 

原因:

這據說是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聲明什麼. 

 

下面給出流浪給的解決辦法: 

//方法一: 

//提前聲明 

class cylinder; 

istream &operator>>(istream& is,cylinder &cy);

 

//方法二:

//不用命名空間 或者 像晨雨那樣寫 

#include<iostream.h> 

 

//方法三: 

class cylinder

    friend istream &operator>>(istream& is,cylinder &cy)//寫在類裏面 

    {

        cout<<"input length:"<<endl; 

        is>>cy.length;

        cout<<"input width:"<<endl; 

        is>>cy.width; 

        cout<<"input height:"<<endl; 

        is>>cy.height; 

        return is;

 

    }

 

..........

 

//方法四:打SP6補丁,貌似不好使。。。(呵呵,是貌似也沒用) 

//方法五:換別的對標準C++支持好的編譯器,如DEV C++/。。。(呵呵)


原文鏈接,感謝原作者

發佈了15 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章