我的问题是您在实践中真正使用嵌套类的频率是多少?在哪些情况下?嵌套类的真正力量是什么,没有它们就不能做什么?
附言请不要解释它是什么,我知道(从技术角度来看
)
最佳答案
我通常使用嵌套类将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/