c++ - C++中的嵌套类

标签 c++ nested-class

我的问题是您在实践中真正使用嵌套类的频率是多少?在哪些情况下?嵌套类的真正力量是什么,没有它们就不能做什么? 附言请不要解释它是什么,我知道(从技术角度来看)

最佳答案

我通常使用嵌套类将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;
};

然后:

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

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

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

关于c++ - C++中的嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3855334/

相关文章:

c++ - 如何获取 ExternalProject 定义的目标的输出路径?

c++ - 在没有系统调用(管道)的线程之间使用 std::istream 和 std::ostream

c# - 我的嵌套类中属性 C# 的设置函数出现 StackOverflowException 错误

ruby - 与嵌套类共享作用域

c++ - 嵌套类的成员函数返回嵌套类的类型

c++ - 在 C++ 中获取属于另一个具有多重继承的类的类的指针

c++ - 在二进制字中查找 1 的最有效方法?

Java:静态嵌套类和反射: "$"与 "."

C++ RNG : how to get different rand generators on different processors?

c++ - 嵌套的 C++ 类可以继承其封闭类吗?