#include<iostream>
#include<string>
using namespace std;
class Student
{
private:
string name;
int age;
public:
Student(const string& s,int n):name(s),age(n){
}
void show(){
cout<<name<<" is "<<age<<" years old";
}
};
class Skill
{
private:
string skill;
friend class CStudent; //说明CStudent类对象可以访问private
public:
Skill(const string& s):skill(s){
}
};
class CStudent: public Student
{
private:
string department;
Skill sk;
public:
CStudent(const string& s1,int n,const string& s2,
const string& s3):Student(s1,n),
sk(s3){
department =s2;}
void show()
{
Student::show();
cout<<" who is in "<<department<<" and good at "<<sk.skill;
}
} ;
int main()
{
CStudent c1("Jeff",20,"BME","running");
c1.show();
}
ATTENTION:
- There is one in the Skill class, which
friend class CStudent
means that CStudent is a friend class of Skill and can access the private of Skill- Declare a Skill class object (has-ar) in CStudent, and then access private through this class object.
- Constructor order: base class, class member object, derived class;
- Destructor order: derived class, class member object, base class