通过引用实现C++多态

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

 1 #include 
 2 
 3 #include 
 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

你可能感兴趣的:(通过引用实现C++多态)