【问题标题】:Is it possible to create a "friend class" in C++?是否可以在 C++ 中创建“朋友类”?
【发布时间】:2009-05-16 01:36:31
【问题描述】:

我知道可以在 C++ 中创建友元函数:

class box
{
friend void add(int num);
private:
int contents;
};

void add(int num)
{
box::contents = num;
return;
}

但是有没有办法创建朋友类?

注意:我知道这段代码可能有很多错误,我不使用友元函数,而且对这门语言还是很陌生;有的话请告诉我。

【问题讨论】:

    标签: c++ class


    【解决方案1】:

    是的 - 在class Box 的声明中,做

    friend class SomeOtherClass;
    

    SomeOtherClass 的所有成员函数将能够访问任何Boxcontents 成员(以及任何其他私有成员)。

    【讨论】:

    • 我假设要定义 SomeOtherClass,您只需编写“SomeOtherClass{public: int someothercontents;};”在 Box 声明之外?
    • @Keand64: SomeOtherClass 将是一个正确定义的类,所以是的,你可以做任何你定义类 Box 的事情。
    【解决方案2】:

    顺便说一句,设计准则是,如果一个类足够接近可以被声明为友元,那么它就足够接近可以在同一个头文件中声明为嵌套类,例如:

    class Box
    {
      class SomeOtherClass
      {
        //some implementation that might want to access private members of box
      };
      friend class SomeOtherClass;
    private:
      int contents;
    };
    

    如果您不想在同一个头文件中将另一个类声明为嵌套类,那么也许您不应该(尽管您可以)将其声明为朋友。

    【讨论】:

      【解决方案3】:

      在您的代码中,您当前正在使用 box 成员“contents”作为 add 函数中的静态成员 (box::contents = num;)

      您应该将内容声明为静态的,如下所示:(然后您还必须对其进行初始化..)

      class box
      {
          friend void add(int num);
          private:
            static int contents;
      };
      
      int box::contents;
      
      void add(int num)
      {
          box::contents = num;
          return;
      }
      

      或者,改变你的 add 函数来接受一个 box 对象和一个 int:

      class box
      {
          friend void add(box *b, int num);
          private:
            int contents;
      };
      
      void add(box *b, int num)
      {
          b->contents = num;
          return;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多