我在 C++ 中有一个必须公开的嵌套类。但我需要它的一些方法对外部世界可见,而其余方法仅对嵌套类可见。即:
class set {
public:
class iterator {
innerMethod();
public:
outerMethod();
}
}
我希望能够为 set 编写一个使用 innerMethod() 的方法。如果我公开它,我也可以从外部访问它,这是我绝对不希望的。有没有办法不做“ friend 类集”的事情就可以做到这一点?
提前致谢!
最佳答案
没有使用 friend
关键字的好方法。
在评论中你说:
In the programming class I currently take, using 'friend' was said to be ill-advised and generally considered "bad programming" for the most part, unless there is really no other way around it. So I try to avoid it as much as possible.
friend
打破了封装,也许这就是为什么你的类主任说这是糟糕的编程。 但是成员函数太破坏封装了,那你为什么要用它们呢?为什么不也避开它们呢? friend
以与成员函数相同的方式打破封装; 因此,如果您习惯于在需要时 使用成员函数,那么您应该也可以在需要时使用friend
。两者都存在于C++中是有原因的!
class set {
public:
class iterator
{
friend class set; //<---- this gives your class set to access to inner methods!
void innerMethod(){}
public:
void outerMethod(){}
};
iterator it;
void fun()
{
it.innerMethod();
it.outerMethod();
}
};
关于c++ - 保持公共(public)嵌套类的一部分仅对嵌套类可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4679983/