考虑以下继承和组合方案。
//示例程序
#include <iostream>
#include <valarray>
using namespace std;
class TapProcessing
{
public:
TapProcessing(){};
virtual ~TapProcessing(){};
virtual void getWeights(valarray<double> &weights) {};
virtual void getPrecisionWeights (valarray<double> &precWeights) {};
virtual const uint &getTapIndex(const uint index) const
{
valarray<uint> a;
a.resize(10);
return a[index];
}; //const {return 0;};
virtual const uint &getTapIndexLow(const uint index) const
{
valarray<uint> a;
a.resize(10);
return a[index];
}; //const {return 0;};;
virtual const uint &getTapIndexHigh(const uint index) const
{
valarray<uint> a;
a.resize(10);
return a[index];
}; //const {return 0;};
};
class StepPrecisionTapProcessing : public TapProcessing
{
public:
StepPrecisionTapProcessing() { _tapIndex.resize(10, 3); }
~StepPrecisionTapProcessing() {};
void getWeights(valarray<double> &weights) { return weights.resize(10);}
virtual const uint &getTapIndex(const uint index) const {return _tapIndex[index]; }
private:
valarray<uint> _tapIndex;
};
class HighPrecisionTapProcessing : public TapProcessing
{
public:
HighPrecisionTapProcessing()
{
_tapIndexLow.resize(10, 4);
_tapIndexHigh.resize(10, 5);
}
~HighPrecisionTapProcessing() {};
void getPrecisionWeights (valarray<double> &precWeights) { return precWeights.resize(10); };
virtual const uint &getTapIndexLow(const uint index) const {return _tapIndexLow[index]; }
virtual const uint &getTapIndeHigh(const uint index) const {return _tapIndexHigh[index]; }
private:
valarray<uint> _tapIndexLow;
valarray<uint> _tapIndexHigh;
};
class Generator
{
public:
Generator(bool isPrecision)
{
if (isPrecision) {_tp = new HighPrecisionTapProcessing();
}
else { _tp = new StepPrecisionTapProcessing(); }
}
~Generator() { delete _tp; }
const uint &getTapIndex(const uint index) const {return _tp->getTapIndex(index); }
const uint &getTapIndexLow(const uint index) const {return _tp->getTapIndexLow(index); }
const uint &getTapIndexHigh(const uint index) const {return _tp->getTapIndexHigh(index); }
private:
TapProcessing *_tp;
};
int main()
{
Generator *G = new Generator(true);
uint index = 5;
cout<<"High tap index is = "<<G->getTapIndexHigh(index)<<endl;
delete G;
return 0;
}
当我运行main时,我得到以下输出,
高抽头指数= 0
这里如果派生类中的getTapIndeHigh声明覆盖了基类中的声明,我们会在输出中看到值为5而不是0.为什么派生类实现不会覆盖基类的类方法虚拟方法?
答案 0 :(得分:0)
问题来自这些方面......
virtual uint getTapIndex(uint index) {};
virtual uint getTapIndexLow(uint index) {};
virtual uint getTapIndexHigh(uint index) {};
他们描述了一个返回uint
的函数,提供了一个实现,但实际上并没有返回值。
如果有合理的基础实施,那么提供它是好的。但是,在这里,您似乎需要pure virtual
方法,使您的班级abstract
。您希望所有派生类都实现一个值。 e.g。
virtual uint getTapIndex(uint index) =0; // require derived classes to implement
virtual uint getTapIndexLow(uint index) { return 0 } // can be overridden, but defaults to returning zero.
virtual uint getTapIndexHigh(uint index) = 0; // require derived classes to implement.