【问题标题】:How can we have friend declaration "friend elaborated-class-name ;" as example in c++? [closed]我们怎样才能有朋友声明“朋友详细类名;”作为 C++ 中的示例? [关闭]
【发布时间】:2016-04-05 10:42:53
【问题描述】:

我对详细的类名感到困惑。如果作为示例进行描述,我将不胜感激。 语法:朋友详细类名;

【问题讨论】:

  • 你的问题毫无意义。为什么不给我们一个小代码示例呢?
  • 改编自这里en.cppreference.com/w/cpp/language/friend 指定以详细类名命名的类、结构或联合作为此类的朋友。这意味着朋友的成员声明和定义可以访问此类的私有成员和受保护成员......我只需要它的 c++ 示例。
  • 你要我们写一个如何使用friend关键字的例子??你需要做一些研究。这不是一个教程网站。

标签: c++ declaration keyword friend


【解决方案1】:

详细的类名意味着class(或struct)关键字+类的实际名称。

像这样使用它:

friend class Klass;

【讨论】:

    【解决方案2】:

    来自 n4140:

    [class.friend]/3:

    未声明函数的友元声明应具有以下形式之一:
    朋友详细说明类型说明符 ;
    朋友简单类型说明符;
    朋友类型名说明符;

    那么你有一个例子:

    class C;
    typedef C Ct;
    class X1 {
      friend C; // OK: class C is a friend
    };
    class X2 {
      friend Ct; // OK: class C is a friend
      friend D; // error: no type-name D in scope
      friend class D; // OK: elaborated-type-specifier declares new class
    };
    

    所以:friend class D; 是详细类型说明符的一个示例。而friend D; 不是并且被称为简单类型说明符 - 这是自 C++11 以来的新内容。

    【讨论】:

      【解决方案3】:

      这是一个演示程序

      #include <iostream>
      
      namespace usr
      {
          int B = 20;
      
          class A
          {
          public:
              A( int x = 0 ) : x( x ) {}
              friend class B;  // using of elaborated type specifier
          private:
              int x;
          };
      
          class B
          {
          public:        
              std::ostream & out( const A &a, std::ostream &os = std::cout ) const
              {
                  return os << a.x;
              }
          };
      }
      
      int main()
      {
          class usr::B b;  // using of elaborated type specifier
          b.out( usr::A( 10 ) ) << ' ' << usr::B << std::endl;    
      }    
      

      它的输出是

      10 20
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-04
        • 1970-01-01
        • 2013-03-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多