C++:有什么方法可以防止抽象基类的任何实例化? [英] C++: any way to prevent any instantiation of an abstract base class?

查看:28
本文介绍了C++:有什么方法可以防止抽象基类的任何实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了拥有纯虚函数之外,还有没有办法防止抽象基类的实例化?

Aside from having a pure virtual function, is there a way to prevent an instantiation of an abstract base class?

我可以做到:

class BaseFoo
{
    virtual void blah() = 0;
};

class Foo : public BaseFoo
{
    virtual void blah() {}
};

但我想避免使用 vtable.(根据 我关于虚拟析构函数的其他问题)

but I'd like to avoid a vtable. (as per my other question about virtual destructors)

微软 ATL 有 ATL_NO_VTABLE 来完成这个(或者至少我认为它就是这样做的......)

Microsoft ATL has ATL_NO_VTABLE to accomplish this (or at least I think that's what it does...)

推荐答案

一个非常明显的方法是声明一个受保护的构造函数,并在非抽象派生类中声明公共构造函数.

A really obvious way is to declare a protected constructor, and to declare public constructors in the non-abstract derived classes.

这当然将正确性的负担转移到派生类,但至少基类受到保护.

This of course shifts the burden of corectness to the derived classes, but at least the base class is protected.

这篇关于C++:有什么方法可以防止抽象基类的任何实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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