C++(基类与派生类类型的转换)

类型转换

1.公有派生类对象可以被当作基类的对象使用,反之则不可

  派生类的对象可以隐含转为基类对象

  派生类的对象可以初始化基类的引用

2.通过基类对象名、指针只能使从基类继承的成员

类型转换规则举例

 1 #include <iostream>
 2 using namespace std;
 3 
 4 class Base1{//基类Base1定义
 5 
 6 public:
 7     void display()const {
 8         cout << "Base1::display()" << endl;
 9     }
10 };
11 
12 class Base2:public Base1{//公有派生类Base2定义
13 public:
14     void display() const{//公有派生类Base2定义
15         cout << "Base2::display()" << endl;
16     }
17 };
18 
19 class Derived :public Base2 {//公有派生类Dervied定义
20 public:
21     void display() const {
22         cout << "Derived::display()" << endl;
23     }
24 
25 };
26 
27 void fun(Base1 *ptr) {//参数为指向基类对象的指针
28     ptr->display();//"对象指针->成员名"
29 
30 }
31 
32 int main() {  //主函数
33     Base1 base1; //声明 Base1类对象
34     Base2 base2; //声明 Base2类对象
35     Derived derived; //声明Derived类对象
36 
37     fun(&base1);
38     fun(&base2);
39     fun(&derived);
40 
41     return 0;
42 }
convert

原文地址:https://www.cnblogs.com/xuelanga000/p/12829091.html