好吧,我来晚了,我知道,我还是想指出另一种可能,如果你想完全隐藏B类的内部:
class A
{
private:
class B;
std::set<B*> b_set;
};
注意在集合中使用指针。但是,还有一个重要的区别:由于只插入了指针,您仍然可以插入指向具有相同内容的不同实例的指针。要解决这个问题,您需要一个自定义比较器:
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const
{
return *x < *y;
}
};
std::set<B*, Less> b_set;
};
请注意(这在上一个答案中没有提到,但在那里也是必需的!)必须为 B 定义一个比较器(B 或引用,not 指针!):
啊.h
#include <set>
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const;
};
std::set<B*, Less> b_set;
};
A.cpp
class A::B
{
friend bool Less::operator() (B const* x, B const* y) const;
bool operator<(B const& other) const
{
return foo < other.foo;
}
int foo;
};
bool A::Less::operator() (B const* x, B const* y) const
{
return *x < *y;
}
如果您出于任何原因想要或需要,这允许从标题中完全隐藏 B。但是,您不能再直接从堆栈中插入对象,因为它们不会被复制,并且您有指向堆栈的指针很快就会变得无效。当不再需要对象时,必须特别注意删除对象,否则会出现内存泄漏。请记住,Java 中没有垃圾收集。如果使用 C++11,可以使用 ::std::unique_ptr, before, ::std::auto_ptr: 来缓解问题:
啊.h
#include <set>
#include <memory>
class A
{
private:
class B;
struct Less
{
bool operator() (B const* x, B const* y) const;
};
std::set<std::unique_ptr<B>, Less> b_set;
};