【发布时间】:2019-04-27 00:02:21
【问题描述】:
对设计模式相当陌生,也许我已经错过了已回答的问题。由于继承问题,我无法练习工厂设计模式。
这是基类
#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();
我一直在寻找其他继承问题,但找不到解决我正在查看的问题的问题。
感谢您的帮助,如果是转载,请见谅
【问题讨论】:
-
您通过在
factory中包含truckfactory和在truckfactory中包含factory来引入循环依赖。
标签: c++ design-patterns factory factory-pattern