友元
- 友元是C++提供的一种破坏数据封装和数据隐藏的机制。
- 通过将一个模块声明为另一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息。
- 可以使用友元函数和友元类。
- 为了确保数据的完整性,及数据封装与隐藏的原则,建议尽量少使用友元。
友元函数
- 若在本类以外其他地方定义一个友元函数(可以是其他类的成员函数,也可以是不属于任何类的非成员函数),在本类体中用friend对其声明,此函数就成为本类的友元函数,可以访问本类的私有成员。
- 友元函数是在类声明中由关键字friend修饰说明的非本类成员函数,在它的函数体中能够通过对象名访问 private成员,protected成员,public成员。
- 作用:增加灵活性,使程序员可以在封装和快速性方面做合理选择。
- 访问对象中的成员必须通过对象名。
-
将普通函数声明为本类友元函数:
#include <iostream> using namespace std; class Box{ public: Box(){} Box(int h ,int w):height(h),width(w){} void volume(); static void show(); friend void display(Box &b); static int length; private: int height; int width; static int c; }; void Box::volume() { cout<<"体积为:"<<height<<"*"<<width<<"*"<<length<<"="<<height * width*length<<endl; } void Box::show() { cout << "静态私有成员c:" << c << " 静态公有成员length:" <<length<< endl; } int Box::length = 5; int Box::c = 6; void display(Box &b) { b.width = 3; b.height = 3; b.c = 3; b.length = 3; b.volume(); b.show(); } void main() { Box b; //调用普通构造函数 display(b); /* 体积为:3*3*3=27 静态私有成员c:3 静态公有成员length:3 */ }
-
友元成员函数(其他类的成员函数)
#include <iostream> using namespace std; class Display; //对Box类的声明 class Box { public: Box() {} Box(int h, int w) :height(h), width(w) {} void volume(Display &); //成员实参必须是Display类对象 static int length; private: int height; int width; static int c; }; class Display { public: Display() { a = 10; b = 5; } void display(); friend void Box::volume(Display &);//将Box类中的volume作为本类友元函数 private: int a; int b; }; void Display::display() { cout << "a=" << a << " b=" << b << endl; } void Box::volume(Display &d) { d.display(); //引用Display私有变量必须加对象名 d.a = 20; d.b = 20; d.display(); cout << "体积为:" << height << "*" << width << "*" << length << "=" << height * width*length << endl; } int Box::length = 5; int Box::c = 6; void main() { Display d; Box b(7,7); b.volume(d); /* a=10 b=5 a=20 b=20 体积为:7*7*5=245 */ }
友元类
- 类为另一个类的友元,则此类的所有成员都能访问对方类的私有成员。
- 声明语法:将友元类名在另一个类中使用friend修饰说明
- 如果声明B类是A类的友元, B类的成员函数就可以访问A类的私有和保护数据,但A类的成员函数却不能访问B类的私有、保护数据。