在C ++中从空基类继承 [英] Inheritance from empty base class in C++

查看:225
本文介绍了在C ++中从空基类继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个名为Node的空基类,然后生成其他类派生的类,如DecisionNode和Leaf。这样做是有意义的,所以我可以利用多态性传递这些不同种类的节点到方法,而不知道在编译时将传递给该方法,但每个派生类不共享任何状态或方法。 / p>

我认为实现这个的最好方法是,不在基类中创建一个额外的纯虚方法,这将增加杂乱,将使构造函数纯虚。在类的头文件中,Node.h因此写道:

  class Node {
private:
virtual Node();
};

在Node.cpp中我写道:

  #includeNode.h
virtual Node :: Node()= 0;

此实现防止Node被另一个类实例化,因为唯一的构造函数是私有的,纯虚拟说明符表示该类是抽象的。但是,这给出编译器错误:

  Node.h:6:21:error:构造函数的返回类型指定无效
Node.h:6:21:error:构造函数不能被声明为虚拟的[-fpermissive]

我的问题是:是否有一个整洁的方法来创建一个空的抽象基类?

解决方案

C ++不支持虚拟构造函数。


§12.1构造函数



12.1.4构造函数不应该是虚拟的(10.3)或静态的(9.4)。


下面的代码不会编译:

  virtual Node :: Node()= 0; 




我的问题是:有一个整洁的方式, base
class?


是的,使析构函数成为纯虚函数,也提供析构函数定义

  class Node 
{
public:
virtual〜Node()= 0
{
}
};


I want to make an empty base class called "Node", and then have other classes derived from this such as "DecisionNode" and "Leaf." It makes sense to do this so I can take advantage of polymorphism to pass these different kinds of nodes to methods without knowing at compile time what will be passed to the method, but each of the derived classes do not share any state or methods.

I thought the best way to implement this, without creating an additional pure virtual method in the base class, which would add clutter, would be to make the constructor pure virtual. In the header file for the class, "Node.h" I therefore wrote:

class Node {
 private:
  virtual Node();
};

and in "Node.cpp" I wrote:

#include "Node.h"
virtual Node::Node() = 0;

This implementation prevents Node from ever being instantiated by another class, since the only constructor is private and uses the pure virtual specifier to indicate that the class is abstract. However, this gives the compiler errors:

Node.h:6:21: error: return type specification for constructor invalid
Node.h:6:21: error: constructors cannot be declared virtual [-fpermissive]

My question is: is there a neat way to make an empty abstract base class?

解决方案

C++ doesn't support virtual constructor.

§ 12.1 Constructors

12.1.4 A constructor shall not be virtual (10.3) or static (9.4).

Below code won't compile:

virtual Node::Node() = 0;

My question is: is there a neat way to make an empty abstract base class?

Yes, make destructor a pure virtual function, also provides destructor function definition

class Node 
{
public:
    virtual ~Node()=0
    {
    }
};

这篇关于在C ++中从空基类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆