代码是摘自《C++高级编程第二版》
具体类图如下:
代码如下:
汽车类:
#include <iostream>
class Car
{
public:
virtual void info() = 0;
};
class Ford : public Car
{
public:
virtual void info() { std::cout<< "Ford" << std::endl; }
};
class Toyota : public Car
{
public:
virtual void info() { std::cout<< "Ford" << std::endl; }
};
汽车工厂类:
#include "Car.h"
class CarFactory
{
public:
CarFactory();
Car* requestCar();
int getNumCarsInProduction() const;
protected:
virtual Car* createCar() = 0;
private:
int mNumCarsInProduction;
};
class FordFactory : public CarFactory
{
protected:
virtual Car* createCar();
};
class ToyotaFactory : public CarFactory
{
protected:
virtual Car* createCar();
};
汽车工厂类中成员的具体定义:
#include "CarFactory.h"
CarFactory::CarFactory() : mNumCarsInProduction(0) {}
Car* CarFactory::requestCar()
{
mNumCarsInProduction++;
return createCar();
}
int CarFactory::getNumCarsInProduction() const
{
return mNumCarsInProduction;
}
Car* FordFactory::createCar()
{
return new Ford();
}
Car* ToyotaFactory::createCar()
{
return new Toyota();
}
C++ Primer 4 中提到 派生类中虚函数的声明必须和基类中的定义方式完全匹配,但有一个例外:返回对基类型的引用或指针的虚函数,派生类中的虚函数可以返回基类函数所返回类型的派生类的引用或指针。说的就是CarFactory中的Car* createCar()函数成员,在派生类FordFactory和ToyotaFactory中的createCar中,返回的是各自类型的车对象的指针。