首页 > 解决方案 > 朋友功能无法访问类的私有数据

问题描述

我一直在尝试了解友元函数,但是下面的问题不起作用。

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

然而,这个程序给出了以下错误:

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;

有人可以解释一下代码有什么问题吗?

标签: c++c++14c++17friend

解决方案


friend void addTheTwo();

使不addTheTwo参数的函数成为类的友元函数。但是你定义了另一个!C++ 允许您定义重载函数,名称相同但参数列表不同(因此不同的函数)。因此:

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

定义了另一个不是朋友的函数...将朋友定义更改为:

friend void addTheTwo(student s1,item i1);

推荐阅读