【问题标题】:Friend Function is not able to access private data of class朋友功能无法访问类的私有数据
【发布时间】:2021-03-13 16:41:25
【问题描述】:

一直在尝试学习友元函数,但是下面的问题还是不行。

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

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

【问题讨论】:

  • 您已将addTheTwo() 添加为好友功能,但您的功能是addTheTwo(student,item)。它们是两种不同的功能。

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


【解决方案1】:
friend void addTheTwo();

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

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

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

friend void addTheTwo(student s1,item i1);

【讨论】:

    【解决方案2】:

    friend 声明的签名需要与引用函数的签名匹配。也就是这个

    friend void addTheTwo();
    

    说 0 元函数 addTheTwo 是朋友,而 this

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

    是一个不相关的 2 参数函数。将您的 friend 声明替换为

    friend void addTheTwo(student, item);
    

    【讨论】:

      【解决方案3】:

      正如编译器所说,您在学生班级中已将标记声明为私有。

      试试这个:

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

      【讨论】:

      • 我认为它使拥有private 数据成员的目的无效。同样,朋友声明也将毫无用处。
      • 让你知道一个类的属性和方法默认是私有的,这对我来说更有用。 (在结构中它们是公开的)。因此,您必须使用该关键字将它们显式声明为公共,如图所示。
      • @avinal 你是对的 - 好的设计使用私有属性,但这不是 OP 提出的问题。
      • 你和@avinal 错了,显然不理解友元函数/类的概念。
      • @avinal:这个答案没有错,但不明智。明智地使用友元函数/类可以解决原本不可能或很难解决的问题。
      猜你喜欢
      • 1970-01-01
      • 2015-11-24
      • 2021-08-16
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多