简体   繁体   English

将Exception创建为内部类是一个好主意吗? C ++

[英]Is it a good idea to create Exception as inner class? C++

So is it a good idea to create Exception as inner class? 那么将Exception创建为内部类是一个好主意吗? I have a feeling that something wrong, but I do not know what exactly.. 我觉得有些不对劲,但我不知道究竟是什么......

For example: 例如:

class A {

  ...something...

public:
  class AException : std::exception {
    ...something...
  }
};

It depends. 这取决于。

A nested class is just that, a nested class. 嵌套类就是嵌套类。 This isn't , so there's nothing magical about inner classes. 这不是 ,因此内部类没有什么神奇之处。

You can use the "outer class" as the namespace. 您可以使用“外部类”作为命名空间。 If this enhances readability, there's something to be said in favour of it. 如果这增强了可读性,那么可以说有利于它。

One disadvantage is that now the exception class is part of the public interface of the class, which 一个缺点是,现在异常类是类的公共接口的一部分,其中

  • prevents you from declaring the exception class in a separate header 阻止您在单独的标头中声明异常类
  • might hinder maintenance of the containing class ( ODR rule ) 可能会妨碍包含类的维护( ODR规则

All else being equal, I'd probably advise against nesting the exception types, since with good naming the benefits should not outweigh the potential drawbacks. 在其他条件相同的情况下,我可能会建议不要嵌套异常类型,因为有了良好的命名,其好处不应该超过潜在的缺点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM