赋值兼容

赋值兼容的规则时在需要使用基类对象的任何地方都可以使用公有派生类对象来替代。公有继承派生类可获得基类中除构造函数,析构函数外的所有成员,能用基类解决的问题,派生类也能解决。更直白点说,如果一个类是从一个基类公有继承过来,那么这个派生类就可以替代基类,反过来基类不能替代派生类。

常用赋值兼容情况:

1.派生类对象赋值给基类对象。

2.派生类对象初始化基类对象引用。

3.派生类对象地址赋值给指向基类对象指针。
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

using namespace std;

class Father
{
public:
void show()
{
cout << "Father show()" << endl;
}

void showFather()
{
cout << "showFather()" << endl;
}
};

class Son : public Father
{
public:
void show()
{
cout << "Son show()" << endl;
}

void showSon()
{
cout << "showSon()" << endl;
}
};

int main()
{
Father father1;
Son son1;
father1 = son1; //子类对象赋值给父类对象
father1.show(); //调用父类中的show()方法
father1.showFather(); //调用父类中的showFather()方法

Son son2;
Father& father2 = son2; //子类对象初始化父类对象引用
father2.show(); //调用父类中的show()方法
father2.showFather(); //调用父类中的showFather()方法

Son son3;
Father* father3 = &son3;//子类对象地址赋值给指向父对象指针
father3->show(); //调用父类中的show()方法
father3->showFather(); //调用父类中的showFather()方法

getchar();
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×