1021 B
1021 B
2.10 类、继承和多态
2.10.1 类
在 C++ 中,我们通过如下方法定义和实现一个类:
/**
* @file Tree.h
*/
class Tree
{
public:
Tree();
~Tree();
char Color[3];
double Height;
double Width;
protect:
virtual void Growth(void);
virtual void Growth(double rate);
string Shape;
private:
void Haha(void);
long Nothing;
}
对应的实现为:
/**
* @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 方法的多态实现。