友元函数无法访问私有数据成员 (c++)
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。 有关更多内容,请参阅:为什么模板只能在头文件中实现?
声明非常好,但是您正在处理此类的哪个实例? 如果您有object.list
,则可以访问list
,但只是list
不引用任何内容。传递类的实例,并使用它来访问list
。
像这样:
void printArray(const Queue& object)
您需要将类实例传递到printArray()
然后才能访问该实例的私有成员。 否则,printArray()
不知道要使用哪个实例。
void printArray(Queue &myQueue){
for (int i = 0; i < myQueue.list.size(); i++){
cout << myQueue.list.at(i) << ", ";
}
cout << endl;
}
我自己,我会这样做:
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
成为一个使用它的非朋友。
相关文章:
- 用于访问容器<T>数据成员的正确 API
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 数据成员SFINAE的C++17测试:gcc vs clang
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 静态数据成员模板专用化的实例化点在哪里
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 使用指针访问数组中的对象数据成员
- 友元函数无法访问私有数据成员 (c++)
- 我可以在 C++ 中将数据成员/变量从其定义之外添加到结构中吗?
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 将私有数据成员添加到野牛生成的类中
- 输入数据成员未按要求工作
- 二维矢量数据成员
- 在类 A 中创建类型为 B 类的向量 - 访问数据 [C++] [成员在两个类中都是私有的]
- 调用在 HXX 文件中声明的静态数据成员
- 是否可以根据其数据成员的类型确定类型的大小
- 访问数据成员(本身是对象)的数据成员,就好像它们是类成员一样
- 使公共数据成员在C++中无法访问
- 从 XML 中读取未指定结构的每个数据成员