C++ 类的友元

  • 友元是C++提供的一种破坏数据封装和数据隐藏的机制
  • 通过将一个模块声明为另外一个模块的友元,一个模块能够引用到另一个模块中本是被隐藏的信息
  • 可以声明友元函数和友元类
  • 为了确保数据的完整性,及数据封装与隐藏的原则,一般很少用友元

1.  友元函数

友元函数是在类声明中由关键字friend修饰说明的非成员函数,在它的函数体中能够通过对象名访问private和protected成员。

作用:增加灵活性,使程序员可以在封装和快速性方面做合理的选择。

访问对象中的成员必须通过对象名。

例:

#include <iostream>
#include<cmath>
using namespace std;
class Point{    //Point类声明
public:
	Point(int x = 0, int y = 0) :x(x), y(y){}
	int getX(){ return x; }
	int getY(){ return y; }
	friend float dist(Point &a, Point &b);
private:
	int x, y;
};

float dist(Point &a, Point &b)
{
	double x = a.x - b.x;
	double y = a.y - b.y;
	return static_cast<float>(sqrt(x*x + y*y));
}

int main()
{
	Point p1(1, 1), p2(4, 5);
	cout << "The distance is: ";
	cout << dist(p1, p2) << endl;

	system("pause");
	return 0;
}

2. 类友元

若一个类为另外一个类的友元,则此类的所有成员都能访问对方类的私有成员。

声明语法:将友元类名在另一个类中使用friend修饰说明。

举例说明:

class A{
   friend class B;
public:
   void display(){
   cout << x << endl;
 }
private:
   int x;
};
class B{
public:
    void set(int i);
    void display();
private:
    A a;
};
void B::set(int i){
    a.x = i;
}
void B::display(){
    a.display();
}

上面的B类中私有成员包含A类的对象a,B类的成员函数定义中想直接调用A类的私有成员x,这个时候就必须进行授权,这个授权就是在A类中将B类声明为友元类。

类的友元关系是单向的:声明B类是A类的友元不等于A类是B类的友元。

发布了59 篇原创文章 · 获赞 25 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m0_37570854/article/details/104998603