C++如何实现不可被继承的类

实现一个不可被继承的类有两种方式:

  1. 将基类的构造函数私有化

因为在C++中,当创建派生类的对象时,会首先调用基类的构造函数,然后再调用派生类的构造函数。因此,构造一个派生类对象会调用两个构造函数:一个是基类的,一个是派生类的。那么基类的构造函数被私有化后,派生类将无法访问基类的构造函数,从而导致编译错误,也就意味着我们实现了一个不可被继承的类。

示例如下:

class NoInheritable {
private:
    NoInheritable() = default;
};

class TryToInheritable : public NoInheritable {};

int main () {
    TryToInheritable tt;
}

编译错误:

noinheritablewithprivate.cpp: In function ‘int main():
noinheritablewithprivate.cpp:11:18: error: use of deleted function ‘TryToInherit::TryToInherit()11 |     TryToInherit tt;
      |                  ^~
noinheritablewithprivate.cpp:8:7: note:TryToInherit::TryToInherit()’ is implicitly deleted because the default definition would be ill-formed:
    8 | class TryToInherit : public NoInheritable {};
      |       ^~~~~~~~~~~~
noinheritablewithprivate.cpp:8:7: error:NoInheritable::NoInheritable()’ is private within this context
noinheritablewithprivate.cpp:5:5: note: declared private here
    5 |     NoInheritable() = default;
      |     ^~~~~~~~~~~~~

但是这个设计方式限制了我们创建基类对象实例的途径,我们只能通过创建一个public静态成员的方式来创建类的实例。

示例如下:

class NoInheritable {
private:
    NoInheritable() = default;
public:
    static NoInheritable createInstance() {
        return NoInheritable();
    }
};
int main () {
    NoInheritable ni = NoInheritable::createInstance();
}
  1. final关键字

C++11提供了一种防止继承发生的方法,即在类名后面跟一个关键字final。

class NoInheritableWithFinal final {};

class TryToInherit : public NoInheritableWithFinal{};

当我们写下这段代码时,会出现一段错误提示:

a 'final' class type cannot be used as a base class

这种方式操作简单,且不会出现其他的附作用,所以最为推荐。

当然,我们也可以通过final关键字限制析构函数的覆盖,来间接限制继承,这里不做赘诉。

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值