C++:类的友元

类的友元

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

友元函数

友元函数是在类声明中由关键字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;
	return 0;
}

友元类
若一个类为另一个类的友元,则此类的所有成员都能访问对方类的私有成员。
声明语法:将友元类名在另一个类中使用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类的友元,B类的成员函数就可以访问A类的私有和保护数据,但A类的成员函数却不能访问B类的私有、保护数据。

猜你喜欢

转载自blog.csdn.net/m0_51354361/article/details/112794193