朋友声明是真实的声明吗? [英] Is the friend declaration a real declaration?

查看:167
本文介绍了朋友声明是真实的声明吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ Primer说:重要的是要了解,朋友声明会影响访问,但从一般意义上来说,它不是声明."

C++ Primer says: "It is important to understand that a friend declaration affects access but is not a declaration in an ordinary sense.".

因此,朋友声明仅应提供对朋友类/函数的访问权限,这不是真正的声明.

So friend declaration should offer access authority only to the friend class/function, it is not a real declaration.

但是,我尝试了该程序,它成功编译并在GCC 5.2.0中输出了 2 ,这是怎么回事?

However, I tried this program, it complied successfully and outputs 2 in GCC 5.2.0, what's wrong?

#include <iostream>

class Tmp {
 public:
  Tmp(int a) : a_(a) {};

 private:
  int a_;

  friend void p(Tmp a) { std::cout << a.a_ << std::endl; }
};

// void p(Tmp a); I commented it, so there is not any declaration statement for p(Tmp a).

int main(void) {
  Tmp a(2);
  p(a);
  return 0;
}

推荐答案

朋友声明和其他声明一样多,因为它们引入了名称.也许C ++ Primer应该选择更好的词.

Friend declarations are as much a declaration as any other, as in they introduce a name; perhaps C++ Primer should have chosen its words better.

但是对于合格或不合格的查找,朋友声明是不可见的(在没有其他同名声明的情况下).您的示例由于 ADL 而起作用,但是正如您从下面看到的那样,仅是一个朋友声明不会使该名称可用于任何其他类型的查找:

A friend declaration however is not visible for qualified or unqualified lookup (in the absence of other declarations of the same name). Your example works due to ADL, but as you can see from the following a friend declaration alone will not make the name available for any other kind of lookup:

struct Tmp {
  friend void p(Tmp);
  friend void q();
};

int main() {
  Tmp a;
  p(a);  // Argument-dependant lookup ==> ok!
  q();   // Unqualified lookup        ==> nope
  ::q(); // Qualified lookup          ==> also nope
}


test.cpp: In function 'int main()':
test.cpp:9:9: error: 'q' was not declared in this scope
       q();
         ^
test.cpp:10:7: error: '::q' has not been declared
       ::q();

这篇关于朋友声明是真实的声明吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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