简体   繁体   中英

Making a friend function access protected members of a class

I wrote the friend function prototype in a class of which protected members I want to access. It looks like this:

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 

Then in the function definition, I tried to access the protected members but I received an error that says that these members are undeclared. Which I understand the compiler doesn't think I am referring to the members in a class, but rather different variables. I don't know how to fix this, as I am still new with practically trying out friend functions. below is my function definition:

template < class elemType >
void incrementByConstant(arrayListType <elemType> &L, int a)
{
   for(int i = 0; i <length; i++)
{
    list[i] += a;
   } }

The errors: "Use of undeclared identifier 'length'", "Use of undeclared identifier 'list'"

I managed to fix the issue by adding "template < class whatever >" before the friend function prototype.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM