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

2021-08-27 15:34:50 字數 2109 閱讀 3685

今天又碰到這個問題,由於以前沒有記筆記的習慣,所以碰到這個問題之後糾結了很久。友元函式本來就是給那些既需要訪問類成員而又不能作為相關類的成員的函式或者類來訪問類私有變數的方法。從這兒可以看出,友元函式會破壞類的封裝性,所以還是少用為妙。

#include "iostream"

using namespace std;

class myclass

myclass(int x, int y)

~myclass()

int sum()

friend ostream &operator<<(std::ostream &strm, const myclass &obj);

private:

int a, b;

};ostream &operator<<(ostream &strm, const myclass &obj)//

int main()

當我在vc6.0上像這樣寫**時,編譯器報如下錯誤:

[quote]compiling...

test.cpp

d:\vcproject\friendtest\test.cpp(33) : error c2248: 'a' : cannot access private member declared in class 'myclass'

d:\vcproject\friendtest\test.cpp(29) : see declaration of 'a'

d:\vcproject\friendtest\test.cpp(33) : error c2248: 'b' : cannot access private member declared in class 'myclass'

d:\vcproject\friendtest\test.cpp(29) : see declaration of 'b'[/quote]

上網一查,發現這是vc6.0的乙個經典bug,是vc6.0對友元函式的支援不夠,同時跟namespace也有關係。

於是,有兩種方式可以解決這個問題:

方式一:注釋掉 using namespace std;加上如下宣告:

using std::cout;

using std::endl;

using std::ostream;

完整**如下:

#include "iostream"

//using namespace std;

using std::cout;

using std::endl;

using std::ostream;

class myclass

myclass(int x, int y)

~myclass()

int sum()

friend ostream &operator<<(std::ostream &strm, const myclass &obj);

private:

int a, b;

};ostream &operator<<(ostream &strm, const myclass &obj)//

int main()

方法二:在程式中不使用 namespace,把頭檔案替換為 .h , 如:

#include "iostream.h"

// using namespace std;

完整源**如下:

#include "iostream.h"

//using namespace std;

class myclass

myclass(int x, int y)

~myclass()

int sum()

friend ostream &operator<<(std::ostream &strm, const myclass &obj);

private:

int a, b;

};ostream &operator<<(ostream &strm, const myclass &obj)//

int main()

c 全域性函式做友元可訪問類的私有成員

1.未設定友元時 不設定友元的情況,類外的全域性函式無法訪問私有成員 2.設定了友元後 設定了友元後 include include using namespace std class building private string m pub void fun int main 3.示例三 和示例...

C 之友元函式不能訪問類的私有成員

無法解決的問題 類中宣告,類外定義的成員函式,導致無法訪問類中的私有成員函式 去掉using namespace std 改變 include 啥的都沒用 蒼了個天,走過路過的幫個忙?學c 嗎,令人頭禿的那種,呵呵 include using namespace std template class...

關於類成員函式中訪問同類物件的私有成員

原址 關於類成員函式中訪問同類物件的私有成員,主要包含以下幾種場景 a 在c 的類的成員函式中,允許直接訪問該類的物件的私有成員變數。b 在類的成員函式中可以訪問同型別例項的私有變數。c 拷貝建構函式裡,可以直接訪問另外乙個同類物件 引用 的私有成員。d 類的成員函式可以直接訪問作為其引數的同型別物...