问题描述
这是我的示例代码,会产生错误:
Here is my example code which produces the error:
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"还可以.
it seems "SortedContainerImpl" went wrong while "ContainerImpl" is fine.
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)
I inheret SortedContainerImpl from ContainerImpl in order to reuse get_size() and get(int)
我不熟悉c ++,此问题的本质是什么,该如何解决?
I'm not familiar with c++, What's the nature of this problem and How can I fix it?
谢谢.
推荐答案
您的SortedContainerImpl
类具有两个单独的Container
基类.一个是虚拟的(通过SortedContainer
类),另一个是非虚拟的(通过ContainerImpl
类).
Your SortedContainerImpl
class has two separate Container
base classes. One is virtual (via the SortedContainer
class) and the other is non-virtual (via the ContainerImpl
class).
SortedContainerImpl
具有Container::get_size()
和Container::get(int)
的具体实现,但是对于通过SortedContainer
进入的虚拟基础,没有实现.
SortedContainerImpl
has concrete implementations of Container::get_size()
and Container::get(int)
for the base that comes in from ContainerImpl
, but not for the virtual base that comes in via SortedContainer
.
解决此问题的一种方法是在SortedContainerImpl
中给出具体的实现:
One way to fix the problem is to give concrete implementations in 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
仅获得一个虚拟的基类Container
:
Another way would be to make Container
a virtual base class of ContainerImpl
, so SortedContainerImpl
would only get the one, virtual, base Container
:
class ContainerImpl : virtual public Container
{
protected:
Impl impl_;
public:
int get_size() {return impl_.data_size_;}
int get(int rowid) {return impl_.get(rowid);}
};
这篇关于g ++“因为以下虚函数是纯净的"与抽象基类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!