[英]Having trouble with inheritance in implementation of C++ factory method
这是设计模式的新手,也许我已经错过了答案。 由于继承问题,我在练习工厂设计模式时遇到了麻烦。
这是基类
#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();
我当时在寻找其他继承问题,但是找不到能够解决我所寻找问题的继承问题。
感谢您的帮助,如果是重新发布,则对不起
有几件事情要考虑:
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
factory
,该班级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
函数以返回各种车辆类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.