c ++中的嵌套类

roo*_*kie 2 c++ nested-class

我的问题是你经常在实践中使用嵌套类以及在哪些情况下?嵌套类的真正力量是什么,没有它们是不可能做到的?PS请不要解释它是什么,我知道(from technical point of view)

ere*_*eOn 6

我通常使用嵌套类将finders对象(与之一起使用std::find_if)嵌入到我的特定类型中.

就像是:

// Dummy example
class Foo
{
  public:
    class finder
    {
      public:

        finder(int value) : m_value(value) {};

        bool operator()(const Foo& foo) { return (foo.m_int_value == value); }

      private:

        int m_value;
    };

   private:

     int m_int_value;

     friend class finder;
};
Run Code Online (Sandbox Code Playgroud)

然后:

vector<Foo> foo_list;
vector<Foo>::iterator foo = 
  std::find_if(foo_list.begin(), foo_list.end(), Foo::finder(4));
Run Code Online (Sandbox Code Playgroud)

当然,这可以在不使用嵌套类的情况下完成.但我发现它非常优雅,因为finder在类定义之外没有用处:

如果我在代码重构的情况下删除了类,那么也应该删除查找程序.

  • @Yogesh:`Foo :: finder`也是一个函数对象.对于更复杂的测试,这比`boost :: bind`或类似的更具可读性. (2认同)