继承:在定义一个新的类B时,如果该类与某个已有的类A相似(指的是B拥有A的全部特点),那么就可以把A作为一个基类,而把B作为基类的一个派生类(也称子类)。
派生类是通过对基类进行修改和扩充得到的。在派生类中,可以扩充新的成员变量和成员函数。 派生类一经定义后,可以独立使用,不依赖于基类。
派生类拥有基类的全部成员函数和成员变量,不论是private、protected、public
在派生类的各个成员函数中,不能访问基类中的private成员。
派生类的写法:
class 派生类名:public 基类名
{
};
派生类对象的内存空间:
派生类对象的体积,等于基类对象的体积,再加上派生类对象自己的成员变量的体积。在派生类对象中,包含着基类对象,而且基类对象的存储位置位于派生类对象新增的成员变量之前。
这个是我自己简单写的:
#include"iostream"
using namespace std;
class father{ //基类
public:
string name;
public:
void setname(const string &name_){name=name_;}
string getname()
{
return name;
}
};
class son :public father{
private:
int money;
public:
void setin(const string & name_,int m)
{
father:: setname(name_);
money=m;
}
void print()
{
cout<<getname()<<endl;
cout<<money<<endl;
}
};
int main()
{
son s;
father f;
f.setname("liu");
s.setin("jia",8);
s.print();
return 0;
}
2.
#include <iostream>
#include <string>
using namespace std;
class CStudent {
private:
string name;
string id; //学号
char gender; //性别,'F'代表女,'M'代表男
int age;
public:
void PrintInfo();
void SetInfo( const string & name_,const string & id_,
int age_, char gender_ );
string GetName() { return name; }
};
class CUndergraduateStudent:public CStudent
{//本科生类,继承了CStudent类
private:
string department; //学生所属的系的名称
public:
void QualifiedForBaoyan() { //给予保研资格
cout << "qualified for baoyan "<< endl;
}
void PrintInfo() {
CStudent::PrintInfo(); //调用基类的PrintInfo
cout << "Department:" << department <<endl;
}
void SetInfo( const string & name_,const string & id_,
int age_,char gender_ ,const string & department_) {
CStudent::SetInfo(name_,id_,age_,gender_); //调用基类的SetInfo
department = department_;
}
};
void CStudent::PrintInfo()
{
cout << "Name:" << name << endl;
cout << "ID:" << id << endl;
cout << "Age:" << age << endl;
cout << "Gender:" << gender << endl;
}
void CStudent::SetInfo( const string & name_,const string & id_,
int age_,char gender_ )
{
name = name_;
id = id_;
age = age_;
gender = gender_;
}
int main()
{
CUndergraduateStudent s2;
s2.SetInfo("Harry Potter" , "118829212",19,'M',"Computer Science");
cout << s2.GetName() << " " ;
s2.QualifiedForBaoyan ();
s2.PrintInfo ();
return 0;
}
输出:
Harry Potter qualified for baoyan
Name:Harry Potter
ID:118829212
Age:19
Gender:M
Department:Computer Science