Merge pull request '更新 'Chapter2_C与C++/2.10_类、继承和多态.md'' (#4) from lion187-patch-1 into master

Reviewed-on: #4
This commit is contained in:
lion187 2021-12-06 15:01:48 +08:00
commit 1c3f54e57d

View File

@ -90,17 +90,17 @@ void Animal::MakeSounds(void)
```cpp
/**
* @file   Dog.hpp
* @file   Puppy.hpp
*/
#pragma once
#include "Animal.hpp"
class Dog : public Animal
class Puppy : public Animal
{
public:
Dog();
virtual ~Dog();
Puppy();
virtual ~Puppy();
protected:
virtual void Growth(void);
@ -110,46 +110,46 @@ protected:
};
```
可以看到,Dog 类覆盖了 Animal 类中两个 Growth 方法,并且通过多态扩充了一个 Growth 方法。看下 Dog 类的实现:
可以看到,Puppy 类覆盖了 Animal 类中两个 Growth 方法,并且通过多态扩充了一个 Growth 方法。看下 Puppy 类的实现:
```cpp
/**
* @file   Dog.cpp
* @file   Puppy.cpp
*/
#include "Dog.hpp"
#include "Puppy.hpp"
#include <iostream>
Dog::Dog()
Puppy::Puppy()
{
this->Height = 0.6;
this->Sounds = "Wang!Wang!Wang!";
}
Dog::~Dog()
Puppy::~Puppy()
{
cout<<"Dog Dead. Wu...Wu...T_T..."<<endl;
cout<<"Puppy Dead. Wu...Wu...T_T..."<<endl;
}
void Dog::Growth(void)
void Puppy::Growth(void)
{
Height += 0.03;
Width += 0.03;
}
void Dog::Growth(double rate)
void Puppy::Growth(double rate)
{
Height *= (1+rate);
Width *= (1+rate);
}
void Dog::Growth(double height, double width)
void Puppy::Growth(double height, double width)
{
Height = height;
Width = width;
}
```
Dog 类的构造函数中,将 Sounds 属性赋值成了 "Wang!Wang!Wang!" 的狗叫声,当我们调用 Dog 对象的 Sound 方法时,就会出现 "Wang!Wang!Wang!" 而不是 Animal 中的 "Bebe..."。这是因为,在初始化 Dog 对象时,先调用了 Animal 的默认构造函数,对来自父类的属性进行了初始化之后,又调用了 Dog 的构造函数,在 Dog 的构造函数中,再次初始化 Sounds 属性,覆盖了原有的 Animal 中的赋值。
Puppy 类的构造函数中,将 Sounds 属性赋值成了 "Wang!Wang!Wang!" 的狗叫声,当我们调用 Puppy 对象的 Sound 方法时,就会出现 "Wang!Wang!Wang!" 而不是 Animal 中的 "Bebe..."。这是因为,在初始化 Puppy 对象时,先调用了 Animal 的默认构造函数,对来自父类的属性进行了初始化之后,又调用了 Puppy 的构造函数,在 Puppy 的构造函数中,再次初始化 Sounds 属性,覆盖了原有的 Animal 中的赋值。
下面我们看看在 main 函数中如何调用这两个类:
@ -158,7 +158,7 @@ void Dog::Growth(double height, double width)
* @file   main.cpp
*/
#include <Animal.hpp>
#include <Dog.hpp>
#include <Puppy.hpp>
int main() {
Animal* animal;
@ -167,17 +167,17 @@ int main() {
animal->Sound(); // 输出 Bebe...
delete animal; // 输出 Dead.
Dog* dog;
dog = new Dog();
dog->Color[0] = 255;
dog->Growth(0.2); // 调用 Animal 类中的 void Growth(double rate) 方法.
dog->Sound(); // 输出 Wang!Wang!Wang!
delete dog; // 输出 Dog Dead. Wu...Wu...T_T... 和 Dead.
Puppy* puppy;
puppy = new Puppy();
puppy->Color[0] = 255;
puppy->Growth(0.2); // 调用 Animal 类中的 void Growth(double rate) 方法.
puppy->Sound(); // 输出 Wang!Wang!Wang!
delete puppy; // 输出 Puppy Dead. Wu...Wu...T_T... 和 Dead.
return 0;
}
```
通过 dog 调用 Growth 方法那句,更能体现类抽象的实质。
通过 puppy 调用 Growth 方法那句,更能体现类抽象的实质。
## 练习