c++ 泛型 模板继承问题
答案:4 悬赏:60 手机版
解决时间 2021-01-31 07:41
- 提问者网友:战魂
- 2021-01-30 12:33
c++ 泛型 模板继承问题
最佳答案
- 五星知识达人网友:杯酒困英雄
- 2021-01-30 13:02
。。。。。。。
VS2012,给你重新写一个。
#include
#include
#include
enum class Type {
ADD,
SUB
};
template
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
class Add : public Operator {
typedef Operator Base;
public:
Op result() override {
return Base::_x + Base::_y;
}
};
template
class Sub : public Operator {
typedef Operator Base;
public:
Op result() override {
return Base::_x - Base::_y;
}
};
class Factory {
public:
template
static Operator *create(Type type) {
switch(type) {
case Type::ADD:
return new Add;
case Type::SUB:
return new Sub;
default:
throw std::invalid_argument("Factory::create");
}
}
};
int main() {
Operator * op = Factory::create(Type::ADD);
op->setX(1);
op->setY(2);
std::cout << "add = " << op->result() << std::endl;
Operator *op2 = Factory::create(Type::SUB);
op2->setX(2);
op2->setY(1);
std::cout << "sub = " << op2->result() << std::endl;
system("pause");
}
VS2012,给你重新写一个。
#include
#include
#include
enum class Type {
ADD,
SUB
};
template
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
class Add : public Operator
typedef Operator
public:
Op result() override {
return Base::_x + Base::_y;
}
};
template
class Sub : public Operator
typedef Operator
public:
Op result() override {
return Base::_x - Base::_y;
}
};
class Factory {
public:
template
static Operator
switch(type) {
case Type::ADD:
return new Add
case Type::SUB:
return new Sub
default:
throw std::invalid_argument("Factory::create");
}
}
};
int main() {
Operator
op->setX(1);
op->setY(2);
std::cout << "add = " << op->result() << std::endl;
Operator
op2->setX(2);
op2->setY(1);
std::cout << "sub = " << op2->result() << std::endl;
system("pause");
}
全部回答
- 1楼网友:迷人又混蛋
- 2021-01-30 15:12
std::auto_ptr CreateOperation(OPERTYPE aType) //差这个">" 吧
{
Operation *ptr = NULL;
{
Operation *ptr = NULL;
- 2楼网友:忘川信使
- 2021-01-30 14:37
无良啊,天杀的啊,无语啊........................
- 3楼网友:猎心人
- 2021-01-30 13:50
两个笔误,template
class OperationFacory
{
public:
std::auto_ptr
{
Operation
switch(aType)
{
case OPER_ADD:
ptr = new OperationAdd
break;
case OPER_SUB:
ptr = new OperationSub
break;
default:
ptr = NULL;
}
return std::auto_ptr
}
};
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯