继承、虚函数、运行时多态 与 静态多态截图

 1 #include <string>
 2 #include <iostream>
 3 
 4 class A{
 5 public: 
 6     virtual std::string toString(){
 7     //std::string toString(){
 8         return "A";
 9     }
10 };
11 
12 class B: public A{
13 public: 
14     //override 防止覆写函数名错误
15     std::string toString() override {
16     //std::string toString(){
17         return "B";
18     }
19 };
20 
21 class C: public B
22 {
23 public: 
24     std::string toString(){
25         return "C";
26     }
27 };
28 //对象指针
29 void print(A* o){
30     std::cout<<o->toString()<<std::endl;
31 }
32 //对象引用
33 void print(A& o){
34     std::cout<<o.toString()<<std::endl;
35 }
36 
37 //虚函数、 基类对象指针、引用
38 int main() {
39     A a;
40     B b;
41     C c;
42     
43     print(&a);
44     print(&b);
45     print(&c);
46     
47     print(a);
48     print(b);
49     print(c);
50     return 0;
51 }

 

原文地址:https://www.cnblogs.com/GoldenEllipsis/p/10994717.html