Pros and cons of using nested C++ classes and enumerations?

前端 未结 13 2128
悲&欢浪女
悲&欢浪女 2020-11-29 23:43

What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called printer, and this class also store

相关标签:
13条回答
  • 2020-11-30 00:15

    Only problem with nested classes that I bumped into yet was that C++ does not let us refer to the object of the enclosing class, in the nested class functions. We cannot say "Enclosing::this"

    (But maybe there's a way?)

    0 讨论(0)
  • 2020-11-30 00:18

    If you put the enum into a class or a namespace, intellisense will be able to give you guidance when you're trying to remember the enum names. A small thing for sure, but sometimes the small things matter.

    0 讨论(0)
  • 2020-11-30 00:19

    I can see a con for nested classes, that one may better use generic programming.

    If the little class is defined outside the big one, you can make the big class a class template and use any "little" class you may need in the future with the big class.

    Generic programming is a powerful tool, and, IMHO, we should keep it in mind when developing extensible programs. Strange, that no one has mentioned this point.

    0 讨论(0)
  • 2020-11-30 00:30

    One con that can become a big deal for large projects is that it is impossible to make a forward declaration for nested classes or enums.

    0 讨论(0)
  • 2020-11-30 00:30

    If you're never going to be using the dependent class for anything but working with the independent class's implementations, nested classes are fine, in my opinion.

    It's when you want to be using the "internal" class as an object in its own right that things can start getting a little manky and you have to start writing extractor/inserter routines. Not a pretty situation.

    0 讨论(0)
  • 2020-11-30 00:30

    paercebal said everything I would say about nested enums.

    WRT nested classes, my common and almost sole use case for them is when I have a class which is manipulating a specific type of resource, and I need a data class which represents something specific to that resource. In your case, output_tray might be a good example, but I don't generally use nested classes if the class is going to have any methods which are going to be called from outside the containing class, or is more than primarily a data class. I generally also don't nest data classes unless the contained class is not ever directly referenced outside the containing class.

    So, for example, if I had a printer_manipulator class, it might have a contained class for printer manipulation errors, but printer itself would be a non-contained class.

    Hope this helps. :)

    0 讨论(0)
提交回复
热议问题