这是产生错误的示例代码:

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++,此问题的性质是什么,我该如何解决?

谢谢大家

最佳答案

您的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将仅获得一个虚拟的基本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);}
};

关于c++ - 带有抽象基类的g++ "because the following virtual functions are pure",我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12615904/

10-11 16:58