c++ 泛型 模板继承问题
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c++ 泛型 模板继承问题相关的知识,希望对你有一定的参考价值。
. 1. 用 C++ 实现一个简单工厂方法 基类 为运算类 Operation,子类 为 AddOperation,SubOperation。2.希望引入模板 使该运算器可运算 int,float 类型数据。
3.调试中 vs2012 提示“ factory.CreateOperation(OPER_ADD) ” 无定义。分数不多,跪求指点
代码如下
typedef enum
OPER_ADD,
OPER_SUB,
OPER_UNDEF
OPERTYPE;
template<typename C>
class Operation
public:
virtual ~Operation()
void SetNumA(const C& aNum)
_NumA = aNum;
void SetNumB(const C& aNum)
_NumB = aNum;
virtual C GetResult() = 0;
protected:
C _NumA;
C _NumB;
;
template<typename C>
class OperationAdd:public Operation<C>
public:
virtual C GetResult()
return _NumA + _NumB;
;
template<typename C>
class OperationSub:public Operation<C>
public:
virtual C GetResult()
return _NumA - _NumB;
;
template<typename C>
class OperationFacory
public:
std::auto_ptr<Operation<C> CreateOperation(OPERTYPE aType)
Operation *ptr = NULL;
switch(aType)
case OPER_ADD:
ptr = new OperationAdd<C>;
break;
case OPER_SUB:
ptr = new OperationSub<C>;
break;
default:
ptr = NULL;
return std::auto_ptr<Operation<C>>(ptr);
;
int _tmain(int argc, _TCHAR* argv[])
OperationFacory<int> factory;
std::auto_ptr<Operation<int>> ptr(factory.CreateOperation(OPER_ADD));
ptr->SetNumA(2);
ptr->SetNumB(3);
cout << ptr->GetResult() << endl;
getchar();
return 0;
两个笔误,
template<typename C>class OperationFacory
public:
std::auto_ptr<Operation<C>> CreateOperation(OPERTYPE aType)//少了一个右尖括号
Operation<C> *ptr = NULL;//Operation是泛型的,得带上<C>
switch(aType)
case OPER_ADD:
ptr = new OperationAdd<C>;
break;
case OPER_SUB:
ptr = new OperationSub<C>;
break;
default:
ptr = NULL;
return std::auto_ptr<Operation<C>>(ptr);
; 参考技术A 。。。。。。。
VS2012,给你重新写一个。
#include <stdexcept>
#include <iostream>
#include <cstdlib>
enum class Type
ADD,
SUB
;
template <typename Op>
class Operator
public:
void setX(const Op & x)
_x = x;
void setY(const Op & y)
_y = y;
virtual Op result() = 0;
virtual ~Operator()
public:
Op _x;
Op _y;
;
template <typename Op>
class Add : public Operator<Op>
typedef Operator<Op> Base;
public:
Op result() override
return Base::_x + Base::_y;
;
template <typename Op>
class Sub : public Operator<Op>
typedef Operator<Op> Base;
public:
Op result() override
return Base::_x - Base::_y;
;
class Factory
public:
template<typename Op>
static Operator<Op> *create(Type type)
switch(type)
case Type::ADD:
return new Add<Op>;
case Type::SUB:
return new Sub<Op>;
default:
throw std::invalid_argument("Factory::create");
;
int main()
Operator<int> * op = Factory::create<int>(Type::ADD);
op->setX(1);
op->setY(2);
std::cout << "add = " << op->result() << std::endl;
Operator<double> *op2 = Factory::create<double>(Type::SUB);
op2->setX(2);
op2->setY(1);
std::cout << "sub = " << op2->result() << std::endl;
system("pause");
本回答被提问者采纳 参考技术B std::auto_ptr<Operation<C> CreateOperation(OPERTYPE aType) //差这个">" 吧
Operation *ptr = NULL; 参考技术C 无良啊,天杀的啊,无语啊........................
以上是关于c++ 泛型 模板继承问题的主要内容,如果未能解决你的问题,请参考以下文章