码迷,mamicode.com
首页 > 编程语言 > 详细

Modern C++ Course [Lecture 5] {Move Semantics, Classes}

时间:2018-12-29 13:36:15      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:img   dea   ima   efi   info   think   ted   etl   and   

 

技术分享图片

 

技术分享图片

 

技术分享图片

here, we‘re just creating a class Square inherited from class Rect.

技术分享图片

compiler calls only Square.Print()

 

 

now we would really like to see what is polymorphism, so we create a reference here.

技术分享图片

技术分享图片

Result is still "square" here.

 

let‘s remove the virtual

技术分享图片

技术分享图片

First we defined a Square object "square", and square.Print() called Square‘s Print().

Then we defined a reference Rect object of square, then compiler would regard rect_ref as a Rect object, and call Rect.Print().

 

 if we change a way to represent the Print() in using another function outside the class definition, in which way we don‘t need to write print function for every object.

技术分享图片

 will receive errors here.

 

 but adding "virtual" and "override" can magically avoid the problem.

技术分享图片

技术分享图片

 

 if we dont add virtual here, the output will always be:

rect 10 10

rect 10 20

 

rather than:

square 10 10

square 10 20

 

I think the idea behind virtual is that designers of C++ didn‘t want to waste time writing functions for classes inherited from this parental class. A reference would be efficient.

 技术分享图片

 

 

delete the "const" will have error, because it‘s overload rather than override 

 技术分享图片

 

 polymorphism only works for reference. dont remove the & !

 技术分享图片

 

 

Let‘s summarize the two important points for polymorphism:

1,  virtual function in parental class

2, use reference to represent objects in the interface definition

 

 

技术分享图片

 

 

 pure virtual func:

技术分享图片

 

技术分享图片

 

 

 

 struct is just class with only public

 技术分享图片

 

 技术分享图片

 

 

技术分享图片

 

just F.Y.I. 

 技术分享图片

 

 

技术分享图片

 

 技术分享图片

in operation will ignore the white place

 

技术分享图片

input is an object of ifstream

getline is actually std::getline

 

技术分享图片

output: define ofstream object "out", and out << 

input: define ifstream object "in", and in >>

 

 技术分享图片

 

 技术分享图片

 

 

技术分享图片

 

Modern C++ Course [Lecture 5] {Move Semantics, Classes}

标签:img   dea   ima   efi   info   think   ted   etl   and   

原文地址:https://www.cnblogs.com/ecoflex/p/10195189.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!