我有一个设计为通用的,用于任何一类,这看起来有点像这样:覆盖基类调用的函数?
class FixedByteStream {
public:
FixedByteStream(const char* source)
{
size = strlen(source);
copy(source);
}
/* Many more constructors here */
protected:
void copy(const char* source)
{
address = allocate();
//...
}
/* Plus other functions that call allocate() */
char* FixedByteStream::allocate()
{
return (char*)malloc(size);
}
}
,我已扩大了这一类,因此,它可以使用特定项目的内存池。
class PooledByteStream : public FixedByteStream {
public:
PooledByteStream::PooledByteStream() : FixedByteStream() {}
protected:
char* PooledByteStream::allocate()
{
return (char*)PooledByteStream::pool.allocate(size);
}
}
PooledByteStream应该是相同到FixedByteStream,与所有的相同的功能和构造,不同之处在于被称为分配时(),它应该从存储器池中检索指针。
但是,PooledByteStream :: allocate()不是有史以来调用。不是来自继承的构造函数,也不是来自其他继承的函数(即调用继承的copy())。从基类继承的任何东西都完全没有意识到allocate()应该现在做一些完全不同的事情。
问题是,我该如何解决这个问题?我如何让继承的函数调用覆盖函数,而不是基类的函数?从基类复制粘贴所有必要的函数会抹杀继承点,所以我假设这不是答案。
注意:我不寻找内存管理或其他方式来达到相同的最终结果的建议。这只是一个例子!
你让虚拟? – chris
你可以发布FixedByteStream的默认构造函数吗? – billz