1.定义Date类 :
Date类中定义了三个私有数据成员(year ,month,day)
2.定义Student类:
在Student类中定义了两个私有数据成员(name[] ,birthday)
3.将Student类 定义为Date类的友元类
4.Student类中的成员函数 都可以使用 Date类中的私有成员
#include<iostream>
using namespace std;
#include<string.h>
class Student;
class Date
{ friend class Student;
private: int year,month,day;
public:
Date(int y=1992,int m=7,int d=1){ year=y;month=m;day=d;}
};
class Student
{ private:
char name[10];
Date birthday;
public:
Student(char *s,int y,int m,int d)
{ strcpy(name,s);
birthday.year=y; birthday.month=m;birthday.day=d; }
void show(){ cout<<name<<endl;
cout<<birthday.year<<"/"<<birthday.month<<"/"<<birthday.day<<endl;
}
};
int main()
{ Student stu1("王闯",1992,7,8);
stu1.show();
}