The fifth week of learning: inheritance and derivation concepts

Inheritance: A as a base class, B as a derived class of A, it is called B inherits A, and A derives B

  1. The derived class has all the member functions and member variables of the base class
  2. Derived classes can be obtained by modifying and expanding the base class
  3. Once the derived class is defined, it can be used independently without relying on the base class
  4. The member function of the derived class brother cannot access the private of the base class

Derived class writing:
class B:public A{...}

Memory space for derived objects

Derived object volume = base object volume + derived object’s own member variable volume
(derived object includes base object)

#include<iostream>
#include<string>
using namespace std;
class Student{
    
    
	private:
		string name;
		string ID;
		int age;
		char gender;
	public:
		void printfinfo();
		void setinfo(const string& s1,const string& s2,int n, char ch);
		string getname(){
    
    return name;}
};

class CStudent:public Student
{
    
    
	private:
		string department;
	public:
		void printfinfo();
		void setinfo(const string& s1,const string& s2,int n, char ch,const string& s3);
		void qualified(){
    
    
			cout<<"qualified for baoyan\n";
		}
};

void Student::printfinfo()
{
    
    
	cout<<name<<"("<<ID<<", "<<gender<<")"<<" is "<<age<<" years old ";
}

void Student::setinfo(const string& s1,const string& s2,int n,char ch)
{
    
    
	name = s1;
	ID =s2;
	age = n;
	gender = ch;
}

void CStudent::printfinfo()
{
    
    
	Student::printfinfo();
	cout<<", he is in "<<department<<" department";
}

void CStudent::setinfo(const string& s1,const string& s2,int n,char ch,const string& s3)
{
    
    
	Student::setinfo(s1,s2,n,ch);
	department = s3;
}

int main()
{
    
    
	CStudent s1;
	s1.setinfo("Jeff","2018224042",20,'M',"BME");
	s1.printfinfo();cout<<endl;
	cout<<s1.getname()<<" is ";
	s1.qualified();
}
  1. Derived classes also write functions of the same name, and call the functions of the base class with the same name in the functions of the same name. This is called coverage.

Insert picture description here

Guess you like

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