A:有元函数是普通函数
B:有元函数为类中的成员函数
C:有元类
下面一一介绍。
A:有元函数是普通函数
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
/**********************************************************************
*普通函数作为有元函数
************************************************************************/
using namespace std;
class XFZ{
public:
XFZ(int A):a(A){}
//friend关键字后面要接有元函数的类型 这里为void类型
friend void Friend(XFZ a);//有元函数一定要有参数,参数类型为所在的类,此为XFZ类,即为XFZ a
void print();
private:
int a;
};
void XFZ::print()
{
printf("消费者的数值为%d\n",a);//print函数是在类中,所以可以操纵类中的私有数据
}
void Friend(XFZ N)
{
N.a = 9;//有元函数可以操控类中的私有数据,这是普通函数不能做到的
printf("消费者的数值改为%d\n",N.a);
}
void main()
{
XFZ test(2);
test.print();
Friend(test);
}
B:有元函数为类中的成员函数
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
/**********************************************************************
*XFZ类中的成员函数为SCZ类中的有元函数
************************************************************************/
using namespace std;
class SCZ;//此处不能省略,一旦省略就会报错,声明SCZ类
class XFZ{
public:
void Friend(SCZ&);
void print();
};
class SCZ{
public:
SCZ(int a):a(a){}
void print();
void p();
friend void XFZ::Friend(SCZ&);//有元函数
private:
int a;
};
void SCZ::print()
{
printf("我是生产者\n");
}
void XFZ::print()
{
printf("我是消费者\n");
}
void XFZ::Friend(SCZ& A)
{
A.a = 9;
//printf()
}
void SCZ::p()
{
printf("生产者的数值是%d\n",a);
}
void main()
{
SCZ test(2);
XFZ test1;
test.print();
test1.print();
test1.Friend(test);
test.p();
}
C:有元类
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
/**********************************************************************
*XFZ类为SCZ类中的有元类
************************************************************************/
using namespace std;
class SCZ;//此处不能省略,一旦省略就会报错,声明SCZ类
class XFZ{
public:
void Friend(SCZ&);
void print();
void xriend(SCZ&);
};
class SCZ{
public:
SCZ(int a):a(a){}
void print();
friend XFZ;//有元函数
private:
int a;
};
void SCZ::print()
{
printf("我是生产者\n");
}
void XFZ::print()
{
printf("我是消费者\n");
}
void XFZ::Friend(SCZ& A)//有元类中的函数都为有元函数,所以都可以访问私有数据
{
A.a = 9;
printf("生产者的值改为%d\n",A.a);
}
void XFZ::xriend(SCZ& B)
{
B.a = 10;
printf("生产者的值改为%d\n",B.a);
}
void main()
{
SCZ test(2);
XFZ test1;
test.print();
test1.print();
test1.Friend(test);
test1.xriend(test);
}