🌈个人主页:羽晨同学
💫个人格言:“成为自己未来的主人~”
我们在之前的文章有提到友元,我们先来看下面的这段包含了友元的代码:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Time
{
friend class Date;
public:
Time(int hour = 0, int minute = 0, int second = 0)
:_hour(hour)
,_minute(minute)
,_second(second)
{
}
private:
int _hour;
int _minute;
int _second;
};
class Date
{
public:
Date(int year = 1900,int month = 1, int day = 1)
:_year(year)
,_month(month)
,_day(day)
{
_t._hour++;
}
private:
int _year;
int _month;
int _day;
Time _t;
};
int main()
{
return 0;
}
在这段代码当中,我们可以看到一个典型的运用了友元函数的代码,在这段代码当中,
Date是Time的友元,但是在这个其中涉及到了一个问题,那就是Time可以访问Date,但是Date却不可以访问Time,
你看,当Date访问Time的私有时,编译器就会进行报错。
接下来,让我们看下面的一端代码:
#include<iostream>
using namespace std;
class A
{
private:
static int k;
int h;
public:
void func()
{}
private:
class B
{
public:
void foo(const A& a)
{
cout << k << endl;
cout << a.h << endl;
}
private:
//int _b;
};
};
int main()
{
cout << sizeof(A) << endl;
A a1;
return 0;
}
在上面的这个代码当中,所呈现出来的,就是我们所要讲到的内部类,内部类是一个独立的类,它不属于外部类,更不能通过外部类的对象去访问内部类的成员,外部类对于内部类没有任何优越的访问权限,
注意:内部类就是外部类的友元类
sizeof(外部类)=外部类,和内部类没有任何关系。
#include<iostream>
using namespace std;
class A
{
private:
static int k;
int h;
public:
void func()
{}
private:
class B
{
public:
void foo(const A& a)
{
cout << k << endl;
cout << a.h << endl;
}
private:
int _b;
};
};
int main()
{
cout << sizeof(A) << endl;
A a1;
return 0;
}