- 派生类对象的体积,等于基类对象的体积,再加上派生类对象自己的成员变量的体积。在派生类对象中,包含着基类对象,而且基类对象的存储位置位于派生类对象新增的成员变量之前。
class CBase
{
int v1,v2;
};
class CDerived:public CBase
{
int v3;
};
#include <iostream>
#include <string>
using namespace std;
class CStudent {
private:
string name;
string id;//学号
char gender;//性别
int age;
public:
void PrintInfo();
void SetInfo(const string & name_,const string & id_,int age_,char gender_);
string GetName(){return name; }
};
void CStudent::SetInfo(const string &name_, const string &id_, int age_, char gender_){
name = name_;
age = age_;
id = id_;
gender = gender_;
}
void CStudent::PrintInfo(){
cout<<"name = "<<name<<" id = "<<id;
}
//本科生类
class CUndergraduateStudent:public CStudent {
private:
string department;//系
public:
void QualifiedForBaoyan(){
cout<<"qualified for baoyan"<<endl;
}
void PrintInfo();
void SetInfo(const string & name_,const string & id_,int age_,char gender_,const string & department_);
};//派生类的写法是:类名:public 基类名
void CUndergraduateStudent::SetInfo(const string & name_, const string & id_, int age_, char gender_, const string & department_){
CStudent::SetInfo(name_, id_, age_, gender_);
department = department_;
}
void CUndergraduateStudent::PrintInfo(){
CStudent::PrintInfo();
cout<<" department = "<<department<<endl;
}
//使用
int main(int argc, const char * argv[]) {
CUndergraduateStudent a;
a.SetInfo("aaa", "123", 10, 'f', "物理系");
cout<<a.GetName()<<endl;
a.QualifiedForBaoyan();
a.PrintInfo();
return 0;
}