C++开发中级


818 浏览 5 years, 4 months

2.3 在子类中替换功能

版权声明: 转载请注明出处 http://www.codingsoho.com/

在子类中替换功能

与子类相关的另一个主要技巧是替换己有的功能。WeatherPrediction类中的showResult()方法急需修改。MyWeatherPrediction可以重写这个方法,以替换原始实现中的行为。

新的MyWeatherPredicrion类定义如下所示:

class MyWeatherPrediction: public WeatherPrediction
{
    public:
        virtual void setCurrentTempCelsius(int inTemp);
        virtual int getTomorrowTempCelsius();
        virtual void showResult();
    protected:
        virtual int converCelsiusToFahrenheit(int inCelsius);
        virtual int converFahrenheitToCelsius(int inFahrenheit);
};

下面给出了一个对用户友好的新实现:

void MyWeatherPrediction::showResult()
{
    cout << "Tomorrow's temperature will be " << getTomorrowTempCelsius() 
            << " degrees Celsius (" << getTomorrowTempFahrenheit() << " degrees Fahrenheit)" << endl;
    cout << "Chance of rain is " << (getChanceOfRain() * 100) << " percent" << endl;
    if(getChanceOfRain() > 0.5){
        cout << "Bring an umbrella!" << endl;
    }
}

对于使用这个类的客户而言,就像旧版本的showResult()不曾存在一样。只要对象是一个MyWeatherPrediction对象,就会调用新版本的方法。
这些改动的结果是,MyWeatherPrediction表现的像一个新类,具有适应更具体作用的新功能。另外,由于利用了超类的已有功能,因此这个类不需要太多的代码。