1:简单设计模式
以计算器为例,为了熟悉模板,同时,使用了模板
模板实现放在.h中
此文件是.h
#pragma once
template <typename T>
class Operation
{
public:
Operation();
virtual ~Operation();
virtual T getResult() = 0;;
T numberA;
T numberB;
T result;
};
template <typename T>
class OperationAdd : public Operation<T>
{
public:
OperationAdd();
virtual ~OperationAdd();
T getResult();
};
template <typename T>
class OperationSub : public Operation<T>
{
public:
OperationSub();
virtual ~OperationSub();
T getResult();
};
template <typename T>
class OperationMul : public Operation<T>
{
public:
OperationMul();
virtual ~OperationMul();
T getResult();
};
template <typename T>
class OperationDiv : public Operation<T>
{
public:
OperationDiv();
virtual ~OperationDiv();
T getResult();
};
template <typename T>
Operation<T>::Operation()
{
}
template <typename T>
Operation<T>::~Operation()
{
}
template <typename T>
OperationAdd<T>::OperationAdd()
{
};
template <typename T>
OperationAdd<T>::~OperationAdd()
{
}
template <typename T>
T OperationAdd<T>::getResult()
{
this->result = this->numberA + this->numberB;
return this->result;
//return T();
};
template <typename T>
OperationSub<T>::OperationSub()
{
};
template <typename T>
OperationSub<T>::~OperationSub()
{
}
template <typename T>
T OperationSub<T>::getResult()
{
this->result = this->numberA - this->numberB;
return this->result;
//return T();
};
template <typename T>
OperationMul<T>::OperationMul()
{
};
template <typename T>
OperationMul<T>::~OperationMul()
{
}
template <typename T>
T OperationMul<T>::getResult()
{
this->result = this->numberA * this->numberB;
return this->result;
//return T();
};
template <typename T>
OperationDiv<T>::OperationDiv()
{
};
template <typename T>
OperationDiv<T>::~OperationDiv()
{
}
template <typename T>
T OperationDiv<T>::getResult()
{
if (this->numberB == 0)
{
std::cout << "input error" << std::endl;
return T();
}
this->result = this->numberA / this->numberB;
return this->result;
//return T();
};
main函数
Operation<int>* operation = nullptr;
char a = 0;
scanf_s("%c",&a);
switch (a)
{
case '+':
operation = new OperationAdd<int>();
break;
case '-':
operation = new OperationSub<int>();
break;
case '*':
operation = new OperationMul<int>();
break;
case '/':
operation = new OperationDiv<int>();
break;
}
operation->numberA = 1;
operation->numberB = 3;
std::cout << operation->getResult() << std::endl;