c++ - 朋友函数无法访问私有数据成员(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
,即使它应该是友元函数。
解决方案
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
到头文件中,因为它是一个模板。有关更多信息,请参见:为什么模板只能在头文件中实现?
推荐阅读
- javascript - Vue如何对表单数据进行分组
- javascript - 将网络摄像头视频渲染到画布时超出最大调用堆栈大小
- html - 基于当前页面的 HTML Wrapper 状态更新
- swift - 类型“String._CharacterView.Index”(又名“String.Index”)不符合协议“FixedWidthInteger”
- python - 【Django】在一个模型中编写所有表定义是不好的做法吗?
- python - ValueError:模型的特征数量必须与输入匹配。模型 n_features 为 356,输入 n_features 为 164
- regex - 如何在 Mushclient 中将任何房间描述与正则表达式匹配
- python - AttributeError:从 JSON 数据读取时,“元组”对象没有“读取”属性
- spring-amqp - 如何监听队列不同的虚拟主机?
- xslt - Solr 7.6 安装什么库和什么版本的 XSLT 以与响应编写器一起使用?