友元了,不管是友元类还是友元函数有应该特点是 比较鲜明的,这个特点就是不管是友元类还是友元函数他们具有一个单向的关系
你可以说a是b的友元,但是你无法说b是a的友元
看一个时间日期类来理解一下吧
class date;
class time{
friend class date;
public:
time(int hour, int minute, int second)
:_year(hour)
, _minute(minute)
, _second(second)
{
}
private:
int _year;
int _minute;
int _second;
};
class date{
public:
date(int year, int month, int day)
: _year(year),
_month(month),
_day(day) {}
void getistime(int hour, int minute ,int second)
{
_t._hour = hour;
_t._mintue = minute;
_t._second = second;
}
private:
int _year;
int _month;
int _day;
time _t;
};
int main()
{
date d(1200, 1, 12);
d.getistime(12, 18, 67);
return 0;
}
再来看一下类中类吧
类中类外部类并没有什么优先的访问权限,更不能通过外部类去调用类不类
*内部类是外部类的友元类,内部类可以通过外部类的成员来访问外部类的所有成员
class A {
private:
static int k;
int h;
public:
class B{
public:
void foo(const A& a)
{
cout << k << endl;//OK
cout << a.h << endl;//OK
}
};
};
int A::k = 1;
int main()
{
A::B b;
b.foo(A());
return 0;
}
本文深入解析C++中的友元概念,包括友元类和友元函数的特点及使用方式,以及类中类的访问权限特性。通过具体代码示例,展示了友元如何打破封装界限,以及内部类作为外部类的友元类可以访问其所有成员。
4万+

被折叠的 条评论
为什么被折叠?



