在 C++ 工厂方法的实现中遇到继承问题

Having trouble with inheritance in implementation of C++ factory method

对设计模式还很陌生,也许我已经错过了已回答的问题。由于继承问题,我在实践工厂设计模式时遇到了麻烦。

这是基础class

 #ifndef FACTORY_H
 #define FACTORY_H

 #include <iostream>
 #include "truckfactory.h"

 class factory{

     public:
         std::string typeOfCar;
         factory(){}

         virtual void identifyCar(){
             std::cout << "This car is a " + typeOfCar << std::endl;
         }

         truckfactory* createTruck(){
             return new truckfactory();}
 };
 #endif

而这就是基地工厂class的subclass。

 #ifndef TRUCKFACTORY_H
 #define TRUCKFACTORY_H

 #include "factory.h"
 class truckfactory : public factory{

     public:
         truckfactory(){
             std::cout <<"TruckFactory made"<<std::endl;
             typeOfCar = "truck";
         }   
 };
 #endif

正在努力实施

 #include "factory.h"

 int main(){

     factory carFactory;
     truckfactory* truck;
     truck = carFactory.createTruck();

     carFactory.identifyCar();
     truck->identifyCar();

     return 0;
 }

然而我运行遇到以下问题

./truckfactory.h:5:29: error: expected class name
class truckfactory : public factory
                            ^
./truckfactory.h:11:13: error: use of undeclared identifier 'typeOfCar'
            typeOfCar = "truck";
            ^
factorytest.cpp:10:12: error: no member named 'identifyCar' in 'truckfactory'
    truck->identifyCar();

我正在查看其他继承问题,但找不到解决我正在查看的问题的问题。

感谢帮助,如有转载请见谅

有几点需要考虑:

  1. 您的代码无法编译的原因在于其结构。您不能(或不应该)让 factory.h 包含 truckfactory.h,然后包含 factory.h。循环依赖会给你带来问题。处理这个问题的正常方法是像这样转发声明 truck_factory
 #ifndef FACTORY_H
 #define FACTORY_H

 #include <iostream>

class truck_factory;

class factory{

     public:
         std::string typeOfCar;
         factory(){}

         virtual void identifyCar(){
             std::cout << "This car is a " + typeOfCar << std::endl;
         }

         truckfactory* createTruck(); //Note definition must be in c++ file
 };
 #endif
  1. 从概念上讲,您的工厂应该构建对象,而不是其他工厂。例如,您可能有一个 class factory,它知道如何制造卡车、汽车、摩托车等。为此,您需要定义一个 vehicle class,然后一个可以根据传入的类型构建正确 class 的工厂。类似于:
class Vehicle {
   public:  
       virtual std::string typeOfCar() const = 0; 
       void identifyCar() {
             std::cout << "This car is a " + typeOfCar << std::endl;
         }
};

class Factory { 
    public:
        Vehicle* create_vehicle(const std::string& type); // need to somehow specify what type you want to create.
};

class Truck : public Vehicle {
    virtual std::string typeOfCar() const { return "truck"; }
};

需要在 cpp 文件中为 return 各种车辆类型定义 create_vehicle 函数。