c++ - 朋友功能无法访问类的私有数据
问题描述
我一直在尝试了解友元函数,但是下面的问题不起作用。
#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;
有人可以解释一下代码有什么问题吗?
解决方案
friend void addTheTwo();
使不addTheTwo
带参数的函数成为类的友元函数。但是你定义了另一个!C++ 允许您定义重载函数,名称相同但参数列表不同(因此不同的函数)。因此:
void addTheTwo(student s1,item i1) {...}
定义了另一个不是朋友的函数...将朋友定义更改为:
friend void addTheTwo(student s1,item i1);
推荐阅读
- github - 镜像 Azure DevOps (Azure Repos) 中的所有 GitHub 活动
- c - 关于在 Unix 中实现系统功能的困惑
- c# - Use bot calling endpoint to listen to meetings/calls between users
- graphql - Looking for code for a server side GraphQL subscription listener
- vb.net - 如何在 VB .NET 中隐藏 Selenium ChromeDriver 控制台
- c - Having trouble concatenating first name and last name
- maven - 为什么 maven deploy 会生成额外的 jars
- amazon-web-services - Dockerfile - 将配置文件复制到适当的容器
- javascript - 调用数据键值的方法?
- bash - 在 bash 脚本中,如何遍历按日期排序的文件