1.友元函数
类里面分别有三个内部保护:分为public、protected和private,但是外部函数只能访问到public的内容,而protected(友元函数和子类)和private(友元函数)通过友元函数访问,关键字friend。我们可以允许一个外部函数获得访问class的protected和private的能力。
为了允许一个外部函数访问class的private和protected成员,必须在calss内部用关键字friend来申明该外部函数的原型,以制定允许该函数共享class的成员。
#include <iostream>
using namespace std;
class Rectangle{
int wigth,height;
public:
void set_value(int,int); //注意这里不能是构造函数,友元函数只能调用类里面的成员函数和成员数据
int area(void){return (wigth*height);}
friend Rectangle oper(Rectangle ¶m);
};
void Rectangle::set_value(int a,int b)//成员函数的命名定义的规则
{
wigth=a;
height=b;
}
Rectangle oper(Rectangle ¶m)
{
Rectangle reti;
reti.wigth=2*param.wigth;
reti.height=2*param.height;
return (reti);
}
int main()
{
Rectangle rect,rectb;
rect.set_value(2,3);
rectb=oper(rect);//这里很明显看到oper不是类里面的成员函数,如果是里面的成员函数的话,可以直接 rectb.oper(rect)
cout<<rectb.area()<<endl;
return 0;
}
如果将其改成类里面的函数的话,代码如下:
#include <iostream>
using namespace std;
class Rectangle{
int wigth,height;
public:
void set_value(int,int);
int area(void){return (wigth*height);}
void test(Rectangle& parm);//引用参数
};
void Rectangle::set_value(int a, int b)
{
wigth=a;
height=b;
}
void Rectangle::test(Rectangle& parm) //如果直接对他的值修改的话,这里是没有返回值的
{
wigth=parm.wigth*3;
height=parm.height*3;
}
int main()
{
Rectangle rect;
Rectangle rectb;
rect.set_value(3,4);
rectb.test(rect);//不用等于号,相当于直接调用里面的函数
cout<<rectb.area()<<endl;;
}
2.友元类
就像我们可以定义一个friend函数,我们也可以定义一个类是另一个的friend,以便允许第二个类访问第一个类的protected和private成员。
#include <iostream>
using namespace std;
class Rectangle_friend; //申明类Rectangle_friend
class Rectangle{
int wigth,height; //默认的是private保护的
public:
void get_vaule(Rectangle_friend &); //引用符号不能少
int area(void){return (wigth*height);}
};
class Rectangle_friend{
int x,y;
public:
void get_data(int ,int);
friend class Rectangle; //申明Rectangle是Rectangle_friend的友元类,即Rectangle可以访问Rectangle_friend 的protected和private成员,反过来不行
};
void Rectangle_friend::get_data(int a,int b)
{
x=a;
y=b;
}
void Rectangle::get_vaule(Rectangle_friend &data)
{
wigth=data.x;
height=data.y;
}
int main()
{
Rectangle_friend data;//声明一个Rectangle_friend 的对象
data.get_data(4,5); //访问成员函数
Rectangle data1;
data1.get_vaule(data);//引用data对象,然后该函数访问类Rectangle_friend的x和y
cout<<data1.area()<<endl;
return 0;
}