简体   繁体   中英

Cannot access private member declared in class, even declared friend class

I have two classes:

class CALLDB;
class CALL
{
friend class CALLDB;
public:
    string GetStart()const;
private:
    string start;
};

And second class:

class CALLDB
{
friend class CALL;
public:
unsigned int Load(istream& fin);
private:
unsigned int numCalls;
};

In the main function, I did this:

int main(){
CALLDB calldata;
cout<<calldata.numCalls;
}

And then it says:

error C2248: 'CALLDB::numCalls': cannot access private member declared in class 'CALLDB'

Why does it happen? Is something wrong with my friend class declaration?

friend class and functions are allowed to access the private data members of a class. so inside the class which is made as friend to another class,you can access the private member.to access the private members inside the friend class or friend function we have to create object for that class and then only we can access the private members. in your example you made CALLDB as friend to CALL and CALL to CALLDB so both the classes can access the private members of other class (ie) you can access the private member of CALLDB in CALL and private member of CALL in CALLDB.but you tried to access the private members from main function which is not a friend to a class.I hope that you understand the concept.here i have given an simple example to understand the concept of friend class .you try that and do your program as per your requirement

#include <iostream>
Using namespace std;
class CALLDB;
class CALL
{
  friend class CALLDB;
  private:
    void display()
      {

       cout<<"\n from Private function of display() of the class CALL ";
     }
};

class CALLDB
  {
    friend class CALL;
    public:
       void output()
         {
           CALL ca;
           cout<<"\n from public function output of CALLDB class ";
           cout<<"\n Calling of private function display of class CALL";
           ca.display();
        }
  };

int main()
 {
    CALLDB cd1;
    cd1.output();
 }

OUTPUT

from public function output of CALLDB class
Calling of private function display of class CALL
from Private function of display() of the class CALL

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