/*定义类X、Y、Z,函数h(X *),满足:
类X有私有成员i,函数Y的成员g(X *)是X的友元函数,实现对X的成员i加1;
类Z是类X的友元类,其成员函数f(X *)实现对X的成员i加5;
函数h(X *)是X的友元函数,实现对X的成员i加10。
在一个文件中定义和实现类,在另一个文件中实现main()函数。*/
头文件:
#include <iostream>
#include <string>
using namespace std;
class X
{
public:
friend class Y;
friend class Z;
friend void h(X* a);
void show()
{
cout << i << endl;
}
private:
int i=0;
};
/*函数Y的成员g(X *)是X的友元函数,实现对X的成员i加1;*/
class Y
{public:
void g(X *a)
{
a->i = a-> i+ 1;
cout << a->i << endl;
}
};
/*类Z是类X的友元类,其成员函数f(X *)实现对X的成员i加5;*/
class Z
{
public:
void f(X* a)
{
a->i = a->i + 5;
cout << a->i << endl;
}
};
void h(X* a)
{
a->i = a->i + 10;
cout << a->i << endl;
}
主函数文件
include <iostream>
#include <string>
#include"xyz.h"
using namespace std;
#define PI 3.1415926
int main()
{
X a;
a.show();
Y b;
b.g(&a);
Z c;
c.f(&a);
h(&a);
}