[英]template inheritance and abstract class
我的以下課程有2個問題。 我遇到了兩個錯誤:第一個可能是關於模板類之間的繼承的問題,另一個是有關在實際上不是抽象類的情況下初始化抽象類的問題(請參見代碼中的注釋)
some_header.h
template <typename T, typename R>
class SDE // abstract class
{
protected:
T drift, diffusion; // drift and diffusion terms
T initialValue;
Interval<R> range;
public:
virtual T GetInitialValue() = 0; // initial condition
virtual T GetDrift() = 0;
virtual T GetDiffusion() = 0;
virtual ~SDE();
};
#include "SDE.h"
#include <cmath>
template <typename T, typename R> // Cox, Ingersoll, Ross sde
class CIRSDE : public SDE<T,R>
{
private:
T kappa, theta, sigma;
public:
CIRSDE(const T& _initialValue,
const Interval<R>& _range,
const T& _kappa,
const T& _theta,
const T& _sigma);
CIRSDE();
~CIRSDE(){};
T GetInitialValue();
T GetDrift(const T& t, const T& r);
T GetDiffusion(const T& t, const T& r);
};
template <typename T, typename R>
CIRSDE<T,R> :: CIRSDE(const T& _initialValue,
const Interval<R>& _range,
const T& _kappa,
const T& _theta,
const T& _sigma)
{
kappa = _kappa;
theta = _theta;
sigma = _sigma;
SDE<T,R> :: initialValue = _initialValue;
SDE<T,R> :: range = _range;
}
template <typename T, typename R>
CIRSDE<T,R> :: CIRSDE()
{
kappa = 1;
theta = 1;
sigma = 1;
SDE<T,R> :: initialValue = 1;
SDE<T,R> :: range = Interval<R>(0,1);
}
template <typename T, typename R>
T CIRSDE<T,R> :: GetDrift (const T& t, const T& r)
{
return kappa * (theta - r);
}
template <typename T, typename R>
T CIRSDE<T,R> :: GetDiffusion(const T& t, const T& r)
{
return sigma * sqrt(r);
}
template <typename T, typename R>
T CIRSDE<T,R> :: GetInitialValue()
{
return initialValue; // ERROR 1
// undeclared identifier "initialValue"
}
main.cpp中
#include "some_header.h"
int main()
{
Interval<int> range(0,5);
CIRSDE<int, int> a (1, range, 3,3,3); //ERROR2
// variable CIRSDE<> is an abstract class
return 0;
}
錯誤1:
template <typename T, typename R>
T CIRSDE<T,R> :: GetInitialValue()
{
return initialValue; // ERROR 1
// undeclared identifier "initialValue"
}
這是查找問題。 標識符initialValue
不依賴於模板參數,因此在替換實際類型之前和不檢入基數之前的第一遍中對其進行了解析(直到您替換類型才知道基數!)
您可以通過像在SDE<T,R>::initialValue
之前一樣進行限定來解決此問題,或者使用this
:
return this->initialValue;
錯誤2
CIRSDE<int, int> a (1, range, 3,3,3); //ERROR2
// variable CIRSDE<> is an abstract class
問題是該庫具有幾個純虛擬函數,您沒有在CIRSDE
提供其定義。 尤其是:
virtual T GetDrift() = 0;
virtual T GetDiffusion() = 0;
請注意,以下類型(派生類型)不會被覆蓋,因為它們的簽名不匹配:
T GetDrift(const T& t, const T& r);
T GetDiffusion(const T& t, const T& r);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.