首页 > 解决方案 > 让友元函数访问类的受保护成员

问题描述

我在我想访问的受保护成员的类中编写了朋友函数原型。它看起来像这样:

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;
   } }

错误:“使用未声明的标识符'长度'”,“使用未声明的标识符'列表'”

标签: c++xcode

解决方案


我设法通过在朋友函数原型之前添加“模板<类任何>”来解决这个问题。


推荐阅读