C++开发中级


789 浏览 5 years, 4 months

2.1 使用继承重用代码WeatherPrediction类

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

WeatherPrediction类

假定您要编写一个简单的天气预报程序,同时给出华氏温度以及摄氏温度。作为程序员,天气预报可能超出了您的研究领域,因此您可以使用可一个第三方的库,这个库可以根据当前温度以及火星与木星之间的距离(这荒谬吗?不,是有点道理的)预测天气。为了保护预报算法的知识产权,第三方的包作为己编译的库分发,但是您可以看到类的定义。WeatherPrediction类的定义如下:

// predict the weather using proven new-age techniques given the current temperature and the distance from Jupiter to Mars. 
// If these are not provided, a guess is still given but it's only 99% accurate.

class WeatherPrediction
{
    public:
        // sets the current temperature in fahrenheit
        virtual void setCurrentTempFahrenheit(int inTemp);
        // sets current distance between Jupiter and Mars
        virtual void setPositionOfJupiter(int inDistanceFromMars);
        // gets the prediction of tomorrow's temperature
        virtual int getTomorrowTempFahrenheit();
        // gets the probability of rain tomorrow. 1 means definite rain, 0 means no chance of rain
        virtual double getChanceOfRain();
        // displays the result to the user in the format: Result x.xx chance. Temp. xx
        virtual void showResult();
        // returns string representation of the temperature
        virtual std::string getTemperature() const;
    protected:
        int mCurrentTempFahrenheit;
        int mDistanceFromMars;        
}

注意这个类将所有方法标记为virtual,因为这个类假定这些方法可能在子类中被重写。
这个类解决了大部分问题。然而与多数情况一样,它与您的需要并不完全吻合。首先,所有的温度都是以华氏温度给出,您的程序还需要处理摄氏温度。此外,showResult()方法的显示方式可能并不是您想要的。