这是我产生错误的示例代码:
struct Impl
{
int data_size_;
int find(int var){return 0;}
int get(int rowid){return 0;}
};
class Container
{
public:
Container() {}
virtual ~Container() {}
virtual int get_size() = 0;
virtual int get(int rowid) = 0;
};
class SortedContainer : virtual public Container {
public:
virtual int find(int var) = 0;
};
class ContainerImpl : public Container
{
protected:
Impl impl_;
public:
int get_size() {return impl_.data_size_;}
int get(int rowid) {return impl_.get(rowid);}
};
class SortedContainerImpl
: public SortedContainer, public ContainerImpl
{
private:
typedef ContainerImpl Base;
public:
int find(int var){return Base::impl_.find(var);}
};
ContainerImpl ci;
SortedContainerImpl sci;
似乎“SortedContainerImpl”出错了,而“ContainerImpl”很好。
g++ 抱怨:
example_b.cpp:42:21: error: cannot declare variable ‘sci’ to be of abstract type ‘SortedContainerImpl’
example_b.cpp:32:7: note: because the following virtual functions are pure within ‘SortedContainerImpl’:
example_b.cpp:13:15: note: virtual int Container::get_size()
example_b.cpp:14:15: note: virtual int Container::get(int)
我从 ContainerImpl 继承 SortedContainerImpl 以便重用 get_size() 和 get(int)
我不熟悉 c++,这个问题的本质是什么,我该如何解决?
谢谢大家。