[英]Friend function cannot access private data member (c++)
我搜索了許多不同的問題,但是找不到適合我特定問題的解決方案。 我有這個隊列的頭文件:
#ifndef HEADERFILE
#define HEADERFILE
#include <iostream>
#include <vector>
using namespace std;
template<class myType>
class Queue{
private:
int size;
vector<myType> list;
public:
Queue(int);
void Enqueue(myType);
myType Dequeue();
myType PeekFront();
int length();
void empty();
myType Index(int);
friend void printArray();
};
#endif
有問題的問題是friend void printArray
。 這是實現文件:
#include "queueTask1.h"
#include <vector>
#include <iostream>
using namespace std;
(Other function implementations)
void printArray(){
for (int i = 0; i < list.size(); i++){
cout << list.at(i) << ", ";
}
cout << endl;
}
嘗試運行此錯誤時指出
在此范圍內未聲明“列表”
但是,它在頭文件中聲明,並且所有其他成員函數都可以正常工作。 由於某種原因, printArray
無法找到私有數據成員list
,即使它應該是一個朋友函數也是如此。
list
是一個非靜態數據成員。 這意味着每個對象都有一個list
。 由於它依賴於對象,因此需要一個對象來訪問其list
。 最簡單的方法是將對象傳遞給類似的函數
// forward declare the function, unless you want to define the function inside the class
template<class ElementType>
friend void printArray(const Queue<ElementType>&);
template<class myType>
class Queue{
//...
// declare the friendship
template<class ElementType>
friend void printArray(const Queue<ElementType>&);
//...
};
// define the function
template<class ElementType>
void printArray(const Queue<ElementType>& q)
{
for (int i = 0; i < q.list.size(); i++){
cout << q.list.at(i) << ", ";
}
cout << endl;
}
您還需要將Queue
的實現移動到頭文件中,因為它是一個temaplte。 有關更多信息,請參見: 為什么只能在頭文件中實現模板?
您需要將類實例傳遞到printArray()
,然后可以訪問該實例的私有成員。 否則, printArray()
不知道要使用哪個實例。
void printArray(Queue &myQueue){
for (int i = 0; i < myQueue.list.size(); i++){
cout << myQueue.list.at(i) << ", ";
}
cout << endl;
}
該聲明非常好,但是您正在處理該類的哪個實例? list
被訪問,如果你有object.list
,只是list
沒有指向任何東西。 傳遞您的類的實例,並使用它來訪問list
。
就像是:
void printArray(const Queue& object)
我自己,我會這樣做:
template<class myType>
class Queue{
// snip ...
public:
// snip ...
template<class F>
friend void foreach_element(Queue& q, F&& f) {
for(auto&&e:list) f(e);
}
template<class F>
friend void foreach_element(Queue const& q, F&& f) {
for(auto&&e:list) f(e);
}
};
template<class myType>
void printArray(Queue<myType> const& q) {
foreach_element(q, [](auto&& e){ std::cout << e << ","; } );
std::cout << std::endl;
}
請注意, printArray
的實現必須放在標頭中,因為它是模板函數。
我暴露了foreach_element
以獲取元素,然后讓printArray
是使用它的非朋友。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.