更新 'Chapter2 C与C++/2.10 类、继承和多态.md'
This commit is contained in:
parent
66932be408
commit
86ee65c4dc
@ -5,6 +5,9 @@
|
|||||||
在 C++ 中,我们通过如下方法定义和实现一个类:
|
在 C++ 中,我们通过如下方法定义和实现一个类:
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
|
/**
|
||||||
|
* @file Tree.h
|
||||||
|
*/
|
||||||
class Tree
|
class Tree
|
||||||
{
|
{
|
||||||
public:
|
public:
|
||||||
@ -16,8 +19,8 @@ public:
|
|||||||
double Width;
|
double Width;
|
||||||
|
|
||||||
protect:
|
protect:
|
||||||
void Growth(void);
|
virtual void Growth(void);
|
||||||
void Growth(double rate);
|
virtual void Growth(double rate);
|
||||||
|
|
||||||
string Shape;
|
string Shape;
|
||||||
|
|
||||||
@ -28,3 +31,45 @@ private:
|
|||||||
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
对应的实现为:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
/**
|
||||||
|
* @file Tree.cpp
|
||||||
|
*/
|
||||||
|
#include <Tree.h>
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
Tree::Tree()
|
||||||
|
{
|
||||||
|
this->Height = 8.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
Tree::~Tree()
|
||||||
|
{
|
||||||
|
cout<<"Dead."<<endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Tree::Growth(void)
|
||||||
|
{
|
||||||
|
Height += 0.2;
|
||||||
|
Width += 0.1;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Tree::Growth(double rate)
|
||||||
|
{
|
||||||
|
Height *= (1+rate);
|
||||||
|
Width *= (1+rate);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Tree::Haha(void)
|
||||||
|
{
|
||||||
|
cout<<"Nothing to do."<<endl;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
在这个类里,我们实现了公有,保护和私有属性和方法。提供了虚方法以允许子类对虚方法进行覆盖。还提供了 Growth 方法的多态实现。
|
||||||
|
|
||||||
|
## 2.10.2 继承
|
||||||
|
Loading…
x
Reference in New Issue
Block a user