友元函数破坏了类的封装和信息隐藏

时间:2022-10-25 17:11:10

在c++中,通过类可以实现数据的封装性和信息隐藏的能力,而友元函数则破坏了类的封装和信息隐藏的能力,使得类的私有属性的成员变量可以被其他类对象的方法直接访问。

#include<iostream>
using namespace std;

class Date;
class Time
{
public:
	Time(double h,double m ,double s) {hour=h;minute=m;sec=s;}
	void display(Date &d);
private:
	double hour;
	double minute;
	double sec;
};

class Date
{
public:
	Date(double m, double d, double y) {month=m;day=d;year=y;}
	friend void Time::display(Date &d);
private:
	double month;
	double day;
	double year;
};


void Time::display(Date &d)
{
	cout << d.year << "-" << d.month << "-" << d.day << " ";
	cout << hour << ":" << minute << ":" << sec << endl;
}


void main()
{
	Time t1(12,30,55);
	Date d1(3,25,2010);
	t1.display(d1);
}

运行结果:

友元函数破坏了类的封装和信息隐藏