这是我的示例代码,它产生错误:
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”没问题.
抱怨:
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,这个问题的本质是什么,我该如何解决?
谢谢大家.
解决方法
您的SortedContainerImpl类有两个单独的Container基类.一个是虚拟的(通过SortedContainer类),另一个是非虚拟的(通过ContainerImpl类).
SortedContainerImpl具有Container :: get_size()和Container :: get(int)的具体实现,用于来自ContainerImpl的基础,但不适用于通过SortedContainer进入的虚拟基础.
解决问题的一种方法是在SortedContainerImpl中给出具体实现:
class SortedContainerImpl : public SortedContainer,public ContainerImpl { private: typedef ContainerImpl Base; public: int find(int var){return Base::impl_.find(var);} int get_size() {return ContainerImpl::get_size();} int get(int rowid) {return ContainerImpl::get(rowid);} };
另一种方法是使Container成为ContainerImpl的虚拟基类,因此SortedContainerImpl只能获得一个虚拟的基础容器:
class ContainerImpl : virtual public Container { protected: Impl impl_; public: int get_size() {return impl_.data_size_;} int get(int rowid) {return impl_.get(rowid);} };