【发布时间】: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)。它们是两种不同的功能。