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

问题描述 投票:1回答:1

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

这是基类

 #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

这是基础工厂类的子类。

 #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();

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

感谢您的帮助,对不起,如果这是转发

c++ design-patterns factory factory-pattern
1个回答
2
投票

有几点需要考虑:

  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. 从概念上讲,你的工厂应该建造物品,而不是其他工厂例如,你可能有一个类factory知道如何建造卡车,汽车,摩托车等。为此,你需要定义一个vehicle类,然后一个工厂,可以根据传入的类型构建正确的类。喜欢:
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文件中定义create_vehicle函数以返回各种车辆类型。

© www.soinside.com 2019 - 2024. All rights reserved.