# 2.10 类、继承和多态 ## 2.10.1 类和多态 在 C++ 中,我们通过如下方法定义和实现一个类: ```cpp /** * @file   Animal.hpp */ #pragma once // 只被编译一次. #include // 使用 C++ 的 string 类. using namespace std; // 使用 std 命名空间. class Animal { public: Animal(); // 构造函数. virtual ~Animal(); // 析构函数. virtual void Sound(void); char Color[3]; // 属性. double Height; double Width; protected: virtual void Growth(void); // 方法. virtual void Growth(double rate); string Sounds; private: void MakeSounds(void); string Shape; }; ``` 可以看到,Animal 类中有两个参数不同的 Growth 方法,这被称作多态,在使用 Animal 对象时,依据调用 Growth 方法时传入的参数个数和类型来判断具体使用哪个 Growth 方法。Animal 类的实现为: ```cpp /** * @file   Animal.cpp */ #include "Animal.hpp" #include Animal::Animal() { this->Height = 8.5; this->Sounds = "Bebe..."; } Animal::~Animal() { cout<<"Dead."<MakeSounds(); } void Animal::Growth(void) { Height += 0.2; Width += 0.1; } void Animal::Growth(double rate) { Height *= (1+rate); Width *= (1+rate); } void Animal::MakeSounds(void) { cout< Dog::Dog() { this->Height = 0.6; this->Sounds = "Wang!Wang!Wang!"; } Dog::~Dog() { cout<<"Dog Dead. Wu...Wu...T_T..."< #include int main() { Animal* animal; animal = new Animal(); animal->Color[1] = 255; 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. return 0; } ``` 通过 dog 调用 Growth 方法那句,更能体现类抽象的实质。 ## 练习 编写“人类”继承于 Animal 类,扩充其“姓名”和“性别”属性,编写“学生”类继承于“人类”,扩充其“成绩”属性,基于这些类,实现学生成绩录入和显示系统。