简体   繁体   中英

Friend Function is not able to access private data of class

I have been trying to learn about friend functions, but the following problem does not work.

 #include <iostream>
    using namespace std;
    class item{
        int cost;
        float price;
        public:
        void getData(){ int a;float b;
            cout << "Please enter cost" <<endl;
            cin >> a;
            cout << "Please enter price" <<endl;
            cin >> b;
            cost =a;
            price=b;
        }
        friend void addTheTwo();
    } i1,i2,i3;
    class student{
        int marks;
        public :
        void getData(){
            int a;
            cout << "Please enter marks";
            cin >> a;
            marks=a;
        }
        friend void addTheTwo();
    }s1;
    void addTheTwo(student s1,item i1){
        cout << s1.marks +i1.cost;
    }
    int main(){
    i1.getData();
    s1.getData();
    addTheTwo(s1,i1);
    return 0;
    }

This program, however, gives the following error:

test10_13_march.cpp: In function ‘void addTheTwo(student, item)’:
test10_13_march.cpp:30:16: error: ‘int student::marks’ is private within this context
   30 |     cout << s1.marks +i1.cost;
      |                ^~~~~
test10_13_march.cpp:19:9: note: declared private here
   19 |     int marks;
      |         ^~~~~
test10_13_march.cpp:30:26: error: ‘int item::cost’ is private within this context
   30 |     cout << s1.marks +i1.cost;
      |                          ^~~~
test10_13_march.cpp:5:9: note: declared private here
    5 |     int cost;

Can someone please explain what is the problem with the code?

friend void addTheTwo();

makes the function addTheTwo taking no parameter a friend function of the class. But you defined another one, C++ lets you define overloaded function. same name but list of args different (so different functions): Thus:

void addTheTwo(student s1,item i1) {...}

defines another function that is not friend... Change the friend definition to:

friend void addTheTwo(student s1,item i1);

The signature of the friend declaration needs to match that of the referenced function. That is, this

friend void addTheTwo();

say that the 0-ary function addTheTwo is a friend, whereas this

void addTheTwo(student s1,item i1){
    cout << s1.marks +i1.cost;
}

is an unrelated 2-argument function. Replace your friend declarations with

friend void addTheTwo(student, item);

Like the compiler says, you have marks declared as private within the student class.

try this:

class student {
  public:
   int marks;
  private:
   // rest of class
};

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