第五周学习:继承和派生概念

继承:A作为一个基类,B作为一个A的派生类,则称为B继承A,A派生B

  1. 派生类拥有基类的所有成员函数和成员变量
  2. 派生类可以通过对基类进行修改和扩充得到
  3. 派生类一经定义,便可以独立使用,不依赖于基类
  4. 派生类哥哥成员函数中不可以访问基类的private

派生类写法:
class B:public A{...}

派生类对象的内存空间

派生类对象体积 = 基类对象体积+派生类对象自己的成员变量体积
(派生类对象包含基类对象)

#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. 派生类也写同名函数,在同名函数里调用基类同名函数,这种叫覆盖。

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/ZmJ6666/article/details/108577618
今日推荐