让我们说我试图为"数学函数"定义一个抽象基类。 - 即看起来y=f(x)
的内容x
和y
都是数字类型,而x
位于"域" f
。这是我的抽象基类可能是什么样的:
template<typename T>
class AbstractFunction{
public:
virtual bool CheckDomain(T) const = 0;
virtual T operator()(T) const = 0;
};
这表示从AbstractFunction
派生的任何具体类必须实现CheckDomain
方法和&#34;评估运算符&#34; ()
。现在我要做的是 require 评估操作符在评估函数之前调用CheckDomain
函数。是否有一种巧妙的方式来做某种部分实施&#34; operator()(T)
?显然,这意味着它不再是纯虚拟的。
我认为我已经弄清楚了以下构造,但我必须遗漏一些东西,因为如果我创建ConcreteFunction f
并尝试评估f(1.0)
,它就不会使用派生类方法(CheckDomain(x)
总是返回0)。
class AbstractFunction{
public:
virtual bool CheckDomain(double) const = 0;
virtual double EvalFunction(double) const = 0;
virtual double operator()(double);
};
double AbstractFunction::operator()(double x){
bool D = CheckDomain(x);
if(D==1){
return EvalFunction(x);
}
else{
std::runtime_error("Error: Out of Domain");
}
}
class ConcreteFunction : public AbstractFunction{
public:
bool CheckDomain(double x) const {(x>0.0)? 1:0;}
double EvalFunction(double x) const {return x*x;}
// Don't need to define operator(), should inherit from AbstractFunction.
};
我确定我错过了一些简单的想法?
答案 0 :(得分:1)
实际上,我的方法有效!我只是按照我对ConcreteFunction::CheckDomain
的定义进行了间隔。我做了域名检查,但没有退回!以下代码根据需要编译和运行:
#include<stdexcept>
#include<iostream>
class AbstractFunction{
public:
virtual bool CheckDomain(double) const = 0;
virtual double EvalFunction(double) const = 0;
virtual double operator()(double) const;
};
double AbstractFunction::operator()(double x) const{
bool D = CheckDomain(x);
if(D==1){
return EvalFunction(x);
}
else{
throw std::runtime_error("Error: Out of Domain");
}
}
class ConcreteFunction : public AbstractFunction{
public:
bool CheckDomain(double x) const {return (x>0.0)? 1:0;}
double EvalFunction(double x) const {return x*x;}
// Don't need to define operator(), should inherit from AbstractFunction.
};
int main()
{
ConcreteFunction f;
std::cout<<"f(1) = "<<f(2.0)<<std::endl; //OK, returns 4
std::cout<<"f(-1) = "<<f(-1.0)<<std::endl; //Throws runtime error, out of domain.
return 0;
}