The fifth week of learning: the constructor of the derived class

#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:

  1. There is one in the Skill class, which friend class CStudentmeans that CStudent is a friend class of Skill and can access the private of Skill
  2. Declare a Skill class object (has-ar) in CStudent, and then access private through this class object.
  3. Constructor order: base class, class member object, derived class;
  4. Destructor order: derived class, class member object, base class

Insert picture description here

Guess you like

Origin blog.csdn.net/ZmJ6666/article/details/108579448