创建没有抽象方法的抽象类 [英] Create an abstract class without an abstract method

查看:86
本文介绍了创建没有抽象方法的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个班级,A,B和C:

I have 3 classes, A, B, and C:

class A
{
/// Some Code
};

class B : public A
{
/// Some Code
};

class c : public B
{
/// Some Code
};

我想使A类和B类成为抽象类,以防止创建它们的实例,但是这两个类都没有抽象方法.即使没有抽象方法,也有办法使类抽象吗?

I want to make class A and B abstract classes in order to prevent creating instances of them, but neither of these two classes have an abstract method. Is there a way to make a class abstract even if it has no abstract methods?

推荐答案

如果您将这些类用作示例代码中所示的基类,则可能是虚拟析构函数.并且由于析构函数是一种方法,因此可以将其设为纯虚拟(抽象")析构函数,以使类本身成为抽象".

Odds are, if you're using the classes as base classes as shown in the sample code, they should have virtual destructors. And because a destructor is a method, you can make this a pure virtual ("abstract") destructor to make the class itself "abstract".

请注意,仍然可以为纯虚拟方法提供实现,因此您可以使用以下代码:

Note that an implementation can still be provided for a pure virtual method, so you can use the following code:

class A
{
  public:
    virtual ~A() = 0; 

/// Some Code
};

class B : public A
{
  public:
    virtual ~B() = 0;

/// Some Code
};

class C : public B
{
  public:
    virtual ~C() = 0;

/// Some Code
};

A::~A()  { }
B::~B()  { }
C::~C()  { }

由于在销毁对象时始终会调用基类析构函数,因此无需在派生类的析构函数中显式调用基类实现.

Because base class destructors are always called when destroying an object, you need not call the base class implementation explicitly in the destructors for derived classes.

这应该给您想要的效果.但是,我目前正在努力为此设计提供引人注目的应用程序.C ++中抽象类的全部目的是定义一个 interface ,除非定义了构成该接口的方法,否则您将没有接口.我只是不够聪明,或者您可能应该重新考虑您的设计.

This should give you the desired effect. However, I'm currently struggling to come up with a compelling application for this design. The whole purpose of an abstract class in C++ is to define an interface, and you cannot have an interface unless there are methods defined that compose that interface. Either I am just not sufficiently clever, or you should possibly rethink your design.

这篇关于创建没有抽象方法的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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