c++ - 让友元函数访问类的受保护成员
问题描述
我在我想访问的受保护成员的类中编写了朋友函数原型。它看起来像这样:
friend void incrementByConstant(arrayListType <elemType>, int a);
protected:
elemType * list; //array to hold the list elements
int length; //to store the length of the list
int maxSize; //to store the maximum size of the list
然后在函数定义中,我尝试访问受保护的成员,但收到一条错误消息,指出这些成员未声明。据我了解,编译器认为我指的不是类中的成员,而是不同的变量。我不知道如何解决这个问题,因为我还是新手,实际上尝试了朋友功能。下面是我的函数定义:
template < class elemType >
void incrementByConstant(arrayListType <elemType> &L, int a)
{
for(int i = 0; i <length; i++)
{
list[i] += a;
} }
错误:“使用未声明的标识符'长度'”,“使用未声明的标识符'列表'”
解决方案
我设法通过在朋友函数原型之前添加“模板<类任何>”来解决这个问题。
推荐阅读
- oracle - 如何执行包含 varchar 的程序
- javascript - 纯 Javascript,无法将变量分配给数组
- dialogflow-es - 为什么 **alpha/beta** 测试人员的 Dialogflow 无法按预期工作?
- json - 在 Python 中从 JSON 分配变量
- laravel - Laravel 中与 ->profiles() 和 ->profiles 的关系有什么区别?
- parameters - p5.js rect() detailX 和 detailY 的用法?
- nosql - Amazon DynamoDB - 加入
- java - Java- pdfBox 是否可以选择打开文件而不是加载文件?
- php - 未捕获的错误:在布尔值上调用成员函数 get_result()
- javascript - 获取php成功输出的ajax返回值为true或false