如何防止类的对象的构造? [英] How to prevent construction of a class's object?

查看:106
本文介绍了如何防止类的对象的构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在任何地方找不到答案。它可以通过使用条件和抛出异常来完成,但是有其他方法吗?

I can't find the answer anywhere. It can be done by using condition and throwing exception but is there any other way to do so?

推荐答案

为什么你想要一个不能在任何情况下构造的类,但是你可以使所有构造函数 private 并且不提供它们的实现。

It isn't clear why you would want a class that cannot be constructed under any circumstances, but you could make all constructors private and provide no implementation for them. This will prevent construction at compile time.

在C ++ 11中,您可以对所有的构造函数使用 delete

In C++11 you can use delete for all the constructors:

class A
{
 public: // or private, doesn't matter.
  A()=delete;
  A(const A&)=delete;
  A(A&&)=delete;
};

这篇关于如何防止类的对象的构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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