c++ - 保持公共(public)嵌套类的一部分仅对嵌套类可见

标签 c++ friend nested-class friend-class

我在 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();
 }
};

看这个:How Non-Member Functions Improve Encapsulation

关于c++ - 保持公共(public)嵌套类的一部分仅对嵌套类可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4679983/

相关文章:

c++ - 用 C++ 制作图表

c++ - 将继承自某个类的所有类加为好友

Java:如何从静态嵌套类引用外部类的非静态字段?

c++ - 可以为嵌套的私有(private)类重载 operator<< 吗?

c++ - 从嵌套类的函数访问父类的非静态成员

c++ - pybind11 中 protected 虚拟析构函数

c++ - 如何访问 mex 文件中 Matlab 结构数组中的数据

c++ - 正在创建重复的 USB 虚拟串行端口 - 这可能是什么原因造成的?

C++ 模板内部类友元运算符重载

c++ - 为什么我不能让这个成员函数成为另一个类的友元?