一、继承和派生
派生类对象包含着基类对象,而且基类对象存储位置位于派生类对象对象新增成员变量之前
#include <iostream>
#include <string>
using namespace std;
class student
{
private:
string name;
string id;//学号
char gneder;//性别
int age;
public:
void printinfo();
void setinfo(const string &name_, const string &id_, int age_, char gender_);
string getname() { return name; }
};
class graduatestudent :public student//研究生继承了student类
{
private:
string department;//系
public:
void baoyan()
{
cout << "qualified for baoyan" << endl;
}
void printinfo()//覆盖
{
student:printinfo();//调用基类的printinfo,输出共性
cout << "department" << department << endl;
}
};
二、继承和复合关系
继承表示基类完全属于派生类,举例:男人和女人有很多相似点,但女人类不可以继承男人类;应该是先写人类,男人类和女人类派生人类。
复合关系举例:每一个圆对象都包含点对象,这个点对象是圆心,但圆并不是点,不是继承关系。
class point {};
class circle
{
point center//圆里面包含点,圆心
};
错误使用:
这种“人中有狗,狗中有人”的做法导致了循环定义。避免循环定义的方法是在一个类中使用另一个类的指针,而不是对象作为成员变量。
正确方法
三、基类派生类同名成员
void derived::access()
{
j = 5;//error,j是基类私有成员变量
i = 5;//引用的派生类的i
base::i = 5;//引用的基类的i
func()//派生类
base::func()//基类的
}
derived obj;
obj.i = 1;
obj.base::i = 1;
protected 只能在派生类定义时访问,在main 函数里面是不可以的。
四、派生类的构造函数
先初始化从基类构造函数
class bug
{
private:
int nlegs; int ncolor;
public:
int ntype;
bug(int legs, int color);//基类构造函数
void printbug(){};
};
class flybug :public bug// flybug 继承bug
{
int nwings;
public:
flybug(int legs, int color, int wings);//声明派生类构造函数
};
//定义flybug构造函数
flybug::flybug(int legs, int color, int wings) :bug(legs, color)//初始化列表;调用基类bug初始化legs 和 color
{
nwings = wings;//wings直接写在构造函数里面就好
}
int main()
{
flybug b(2, 3, 4);
b.printbug();
b.ntype = 1;
b.nlegs = 2;//error
}
五、public 继承的赋值兼容规则
class base{};
class derived :public base{};
base b;
derived d;
1、派生类对象可以赋值给基类对象.(派生类就是一个基类对象)
b=d;//d里面包含的b里面的内容赋值给b
2、派生类对象可以初始化基类引用
base &br=d;//
3、派生类对象的地址可以赋值给基类指针
base *pb=&d;
#include <iostream>
using namespace std;
class base//基类
{
public:
int n;
base(int n) :n(i)//构造函数初始化列表
cout << "base" << n << "constructed" << endl;
~base()//析构函数
{
cout << "base" << n << "destructed" << endl;
}
};
class derived :public base//儿子辈类
{
public:
derived(int i) :base(i)//初始化列表,先调用基类构造函数base初始化i
{
cout << "derived constructed" << endl;
}
~derived()//析构函数
{
cout << "derived destructed" << endl;
}
};
class morederived :public derived//孙子辈类,只列出直接上层类
{
public:
morederived() :derived(4)
{
cout << "morederived constructed" << endl;
}
~morederived()//析构函数
{
cout << "morederived destructed" << endl;
}
};
int main()
{
morederived obj;
return 0;
}