首页 > 解决方案 > 朋友函数无法访问私有数据成员(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;
}

尝试运行此错误时指出

'list' 未在此范围内声明

但是它是在头文件中声明的,并且所有其他成员函数都可以正常工作。由于某种原因printArray找不到私有数据成员list,即使它应该是友元函数。

标签: c++friend

解决方案


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到头文件中,因为它是一个模板。有关更多信息,请参见:为什么模板只能在头文件中实现?


推荐阅读