C++中的继承小结(1)
概述
C++中继承的方式有三种public,private,protected。子类根据继承方式继承父类的成员函数和数据成员。
书写格式
1
class <新建子类名>: public <父类名>{};
调用构造函数、析构函数顺序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27class Member {
public:
Member() { cout << "create Member" << endl; }
~Member() { cout << "delete Member" << endl; }
};
class Base {
public:
Base() { cout << "create Base " << endl; }
~Base() { cout << "delete Base " << endl; }
};
class Sub :public Base{
public:
Sub() { cout << "create Sub " << endl; }
~Sub() { cout << "delete Sub" << endl; }
private:
//Member m;
protected:
Member m;
};
int main(void)
{
Sub* a = new Sub();
delete a;
system("pause");
return 0;
}输出:
1
2
3
4
5
6create Base
create Member
create Sub
delete Sub
delete Member
delete Base先调用父类构造函数,然后生成数据成员调用成员的构造函数,最后调用子类的构造函数,析构函数顺序相反。
把基类的析构函数写成虚函数virtual
上面定义基类Base时,析构函数不是虚函数。如果把main函数写成如下,左边对基类赋值。
1 |
|
执行结果:
1
2
3
4create Base
create Member
create Sub
delete Base
只释放了基类,没有对所有的资源回收。
把基类的析构函数写成:
1
2
3
4
5 class Base {
public:
Base() { cout << "create Base " << endl; }
virtual ~Base() { cout << "delete Base " << endl; }
};
1
2
3
4
5
6create Base
create Member
create Sub
delete Sub
delete Member
delete Base
所以基类的析构函数写成虚函数
子类给父类赋值
- 子类赋值给父类引用
- 子类赋值给父类指针
- 子类直接赋值给父类
前两种调用子类成员,第三种调用父类成员。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27class Base {
public:
virtual void show()
{
cout << "this is Base !" << endl;
}
};
class Sub :public Base{
public:
void show()
{
cout << "this is Sub !" << endl;
}
};
int main(void)
{
Sub s = Sub();
Base& a = s;
Base* b = &s;
Base c = s;
a.show();
b->show();
c.show();
system("pause");
return 0;
}输出:
1
2
3
4
5
6this is Sub !
this is Sub !
this is Base !纯虚函数 、 抽象类
多重继承
class <新建子类名>: public <父类名1>,public <父类名2>,...{};
如果子类调用父类中的重名函数:
1
2Sub.Base1::show();
Sub.Base2::show()
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!