通过引用实现C++多态

     一般的大家的印象中要实现对象的多态调用,必须用指针来实现,其实引用也可以实现相同的效果。看下面的例子:

 1 #include <iostream>
 2 
 3 #include <cstdio>
 4 
 5 class Object {
 6 
 7   std::string type_name;
 8 
 9 protected:
10 
11   explicit Object(std::string const& type_name) : type_name(type_name) {};
12 
13 public:
14 
15   Object() : type_name("Object") {};
16 
17   Object(Object const &other) : type_name(other.type_name) {};
18 
19   virtual void print() { std::cout << type_name; };
20 
21   virtual ~Object() {};
22 
23 };
24 
25  
26 
27 class Door : public Object {
28 
29   std::string handle;
30 
31 public:
32 
33   Door() : Object("Door"), handle("normal") {}
34 
35   explicit Door(std::string const &handle) : Object("Door"), handle(handle) {}
36 
37   Door(Door const &other) : Object(other), handle(other.handle) {}
38 
39   virtual void print() { Object::print(); std::cout << " " << handle << std::endl; }
40 
41   virtual ~Door() {}
42 
43 };
44 
45  
46 
47 class Book : public Object {
48 
49   std::string title;
50 
51   std::string author;
52 
53 public:
54 
55   Book() : Object("Book"), title(), author() {}
56 
57   Book(std::string author, std::string title) : Object("Book"), title(title), author(author) {}
58 
59   Book(Book const &other) : Object(other), title(other.title), author(other.author) {}
60 
61   virtual void print() { Object::print(); std::cout << " " << title << " by " << author << std::endl; }
62 
63   virtual ~Book() {}
64 
65 };
66 
67  
68 
69 void print(Object& object) {
70 
71   object.print();
72 
73 }
74 
75  
76 
77 int main(int argc, const char * argv[])
78 
79 {
80 
81   Object object;
82 
83   Door door("simple");
84 
85   Book book("program", "C++");
86 
87   print(object);
88 
89   std::cout << std::endl;
90 
91   print(door);
92 
93   print(book);
94 
95   system("pause");
96 
97 }

 

可以猜下输出应该是什么,我在dev C++下编译通过,输出如下:

Object
Door simple
Book C++ by program

 

原理还是比较简单的,主要是理解引用底层是怎么实现的。

C++ 文档只规定了引用该实现什么样的功能,却没有说明怎么实现,在底层引用其实是根据const 指针来塑模的,列如

 int & r = i;

在背后的实现可能为

int * const ptr = &i;

然后

r = 9;

等价于

*ptr = 9;

所以说引用也可以实现相同的多态功能。这也解释了引用的特性。

转载于:https://www.cnblogs.com/dxnbd/p/3139806.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值