7-1友元函数
时间: 2023-11-27 22:05:21 浏览: 30
友元函数是一种特殊的函数,它可以访问包含它的类的私有成员和保护成员。它不是类的成员函数,但可以被声明为该类的友元。声明为友元的函数可以在不实例化该类对象的情况下访问该类的私有成员和保护成员。
友元函数的声明方式为:
```
friend 返回类型 函数名(参数列表);
```
在类的定义中,我们可以将友元函数声明为该类的友元函数:
```
class MyClass {
public:
MyClass(int a): num(a) {}
friend void printNum(MyClass obj); // 声明友元函数
private:
int num;
};
void printNum(MyClass obj) {
cout << obj.num << endl; // 可以访问 MyClass 的私有成员 num
}
int main() {
MyClass obj(10);
printNum(obj); // 调用友元函数
return 0;
}
```
在上面的例子中,`printNum()` 被声明为 `MyClass` 的友元函数,因此可以访问 `MyClass` 的私有成员 `num`。在 `main()` 函数中,我们创建了一个 `MyClass` 对象 `obj`,并将其传递给 `printNum()` 函数,该函数可以访问 `obj` 的私有成员 `num`。
相关问题
7-3 友元函数 分数 30 作者 east 单位 浙江大学 C++考试正在进行。请设计一个学生类student,学号、本次考试成绩是其私有数据成员,同时有一个计算本次考试平均成绩的友元函数 double average(student *p,int count) 以上类名和友元函数的形式,均须按照题目要求,不得修改。 输入是 学号([00001,99999])和成绩,以0结束。(不超过100个学生) 输出是平均成绩。 输入样例: 10001 90 10002 93 0 输出样例:91.5
题目要求的类和友元函数如下:
```c++
class student {
private:
int id; // 学号
int score; // 本次考试成绩
public:
friend double average(student *p, int count);
};
double average(student *p, int count) {
double sum = 0;
for (int i = 0; i < count; i++) {
sum += p[i].score;
}
return sum / count;
}
```
完整代码如下:
(2) 将运算符+和-重载为 complex 类的友元函数。 #include<iostream.h> class complex { public: complex(double r=0.0,double i=0.0) { real=r; imag=i; } //构造函数 friend complex operator + (complex c1,complex c2); //重载运算符+为友元函数 friend complex operator - (complex c1,complex c2); //重载运算符-为友元函数 void display(); //显示复数的值 private: //私有成员 double real; double imag; }; 完成该类的实现并编译运行该程序。
完整实现代码如下:
```cpp
#include<iostream>
using namespace std;
class complex {
public:
complex(double r = 0.0, double i = 0.0) {
real = r;
imag = i;
} //构造函数
friend complex operator+(complex c1, complex c2); //重载运算符+为友元函数
friend complex operator-(complex c1, complex c2); //重载运算符-为友元函数
void display(); //显示复数的值
private: //私有成员
double real;
double imag;
};
complex operator+(complex c1, complex c2) {
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator-(complex c1, complex c2) {
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
void complex::display() {
cout << "(" << real << ", " << imag << "i)" << endl;
}
int main() {
complex c1(1, 2);
complex c2(3, 4);
complex c3 = c1 + c2;
complex c4 = c1 - c2;
c1.display();
c2.display();
c3.display();
c4.display();
return 0;
}
```
运行结果:
```
(1, 2i)
(3, 4i)
(4, 6i)
(-2, -2i)
```
可以看到,重载后的运算符+和- 可以直接对两个复数对象进行运算,且结果正确。