将一个朋友声明注入一个命名空间,Eckel,Vol1,pg:440? [英] Injection of a friend declaration into a namespace, Eckel, Vol1, pg:440?

查看:200
本文介绍了将一个朋友声明注入一个命名空间,Eckel,Vol1,pg:440?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解一个朋友声明的注入到命名空间:

I'm trying to understand injection of a friend declaration into a namespace:

#include <iostream>
using namespace std;

namespace Z { //forward declaration
  class X;
}

class Y {
   public:
   void func(Z::X*, int);
 };

namespace Z {
  class X {
    int i;
    public:
    X() : i(999) {}
    friend void Y::func(Z::X*, int);
    void print(void) { cout << i << endl; }
  };
}


void Y::func(Z::X* ptr, int i)
{
  ptr->i = 40;
}

int main(void)
{
  Z::X zx;
  zx.print();

  Y y;
  y.func(&zx, 40);
  zx.print();

  using namespace Z;
//  func(&zx, 30); DOES NOT WORK
}




friendInject.cc:39:错误:'func'没有在这个范围内声明
这本书说:你可以通过
在一个封闭类中声明一个朋友声明。 现在函数you()是
命名空间Me的成员。

friendInject.cc:39: error: 'func' was not declared in this scope The book says: "You can inject a friend declaration into a namespace by declaring it within an enclosed class". "Now the function you() is a member of the namespace Me."

这是什么意思?我试过Y :: func,但也许只适用于
静态成员函数

What exactly does this mean?? I tried Y::func but that perhaps works only for static member functions??

推荐答案

C ++ 11标准7.3.1.2(3)说:

C++11 Standard 7.3.1.2 (3) says:

如果在非本地类中的一个朋友声明首先声明一个类或函数 [footnote:

"If a friend declaration in a nonlocal class first declares a class or function [footnote: this implies that the name of the class or function is unqualified] the friend class or function is a member of the innermost enclosing namespace."

因此,任何不合格的类或函数是非限定的 em> friend函数声明在最内层的命名空间中引入了一个自由函数; (可能)书中引用了注入命名空间。

So any unqualified friend function declaration introduces a free function in the innermost enclosing namespace; (probably) the book referes to this as to "injection into namespace".

注意,甚至可以在朋友声明中定义(实现)一个函数:

Note that it is even possible to define (implement) a function inside friend declaration:

namespace Z
{
  class C
  {
    friend void f(void){/*do something*/}
  };
}

这个朋友声明不仅injects命名空间Z(f不是类C本身的成员!),因此Z :: f不需要其他声明或定义。

This friend declaration not only "injects" but also implements free function f in the namespace Z (f is not a member of class C itself!), so no other declarations or definitions are needed for Z::f.

对于你的例子, / p>

As to your example,

friend void Y::func(Z::X*, int);

限定的(以命名空间/类名称为前缀) '声明一个函数,它只引用先前在类Y中声明的成员函数Y :: func。这样的朋友声明没有注入。

is qualified (prefixed with namespace/class name), so it doesn't declare a function, it only refers to a member function Y::func previously declared in class Y. Such friend declarations "injects" nothing.

这篇关于将一个朋友声明注入一个命名空间,Eckel,Vol1,pg:440?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆