如何扩展自己的函数
计算器功能强大与否,主要是看函数功能是否强大。所以在设计的最初就把能够简单的扩展函数功能作为关键的设计目标之一。有没有做到呢?实际看一下代码应该最能说明问题。
先是头文件。
#ifndefACOSDFUN_H
#define ACOSDFUN_H
#include"calculatefunction.h"
class AcosdFun : public CalculateFunction
{public:
AcosdFun();
virtual QString getName();
virtual QString getInstruction();
virtual bool execute(QList<double> paraList, double& result, QString& message);
};#endif // ACOSDFUN_H
代码是16行,实际上需要动的,只有类名和防止重复引用的宏定义,算4行吧。
然后是实现部分。
#include"acosdfun.h"
#include "functionmanager.h"
#include <math.h>
static FunctionManager::FunctionRegister acosRegister(new AcosdFun());
AcosdFun::AcosdFun()
{}QString AcosdFun::getName()
{return "acosd";
}QString AcosdFun::getInstruction()
{QString strInstruction;
strInstruction += "acosd(x) -\r\n";
strInstruction += "Arccosine (inverse cosine) function. Result in degrees.\r\n";
strInstruction += "Argument type and attributes\r\n";
strInstruction += "x must be of type real. Its value must satisfy the inequality |X| <= 1.\r\n";
return strInstruction;
}bool AcosdFun::execute(QList<double> paraList, double& result, QString& message)
{if(paraList.count() != 1)
{
message = "Acosd:Invalid parameter count";
return false;
}
double para = paraList.first();
clearError();
result =acos(para) * 180 / M_PI;
return checkError(message);
}
这个类是角度单位的反余弦函数的实现。空行算在内也只有38行。
第6行可能比较费解,是用来登录函数的。有了这一行,就能在函数���表中看到自己定义的函数了。
如果是简单的函数的话,相信15分种可以搞定。
只要在工程文件加入两个文件就可以扩展函数功能,不能再简单了吧。
