GCC中的朋友功能范围 [英] Scope of friend function in GCC

查看:137
本文介绍了GCC中的朋友功能范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据标准:


在类中定义的朋友函数位于类的(词法)范围内,

那么为什么heck没有这个工作(测试了几个GCC版本)?

  #include< iostream> 
使用namespace std;

class A
{
friend void function(){cout<< 文字<< ENDL; };
};

// void void function();

int main()
{
function();
返回0;
}

取消注释当然可以解决问题。 b
编辑(gcc输出):

 (xterm)$ g ++ -ansi -pedantic -Wall  - Wextra test.cpp 
test.cpp:函数'int main()':
test.cpp:13:11:错误:'function'未在此范围内声明


解决方案

引用表示以下内容 - 代码位于类,这样,非限定名称查找将特别表现出来。

$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ typedef int类型;

朋友void function(){
type foo; / *类型可见* /
};
};

如果您已经在命名空间范围中定义了function,那么type将不可见 - 你将不得不说A :: type。这就是为什么它在下一句中说:在课堂外定义的朋友功能不是。。名称定义中的非限定名称查找称为


名称查找名称用于定义朋友函数(11.4)在类中内联定义
授予友谊应按照成员函数定义中查找的描述进行。如果朋友
函数没有在授予友谊的类中定义,那么朋友函数定义
中的名称查找应按照在名称空间成员函数定义中查找的描述进行。


< blockquote>

所以你引用的文本并非真正需要规范 - 规范的非限定名称查找已经涵盖了它。


According to the standard:

A friend function defined in a class is in the (lexical) scope of the class in which it is defined.

Then why the heck doesn't this work (several versions of GCC tested)?

#include <iostream>
using namespace std;

class A
{
  friend void function() { cout << "text" << endl; };
};

// void function();

int main()
{
  function();
  return 0;
}

Uncommenting the declaration of course solves the problem.

Edit (gcc output):

(xterm) $ g++ -ansi -pedantic -Wall -Wextra test.cpp 
test.cpp: In function ‘int main()’:
test.cpp:13:11: error: ‘function’ was not declared in this scope

解决方案

The quote means that the following works - the code is in the lexical scope of the class, such that unqualified name lookup will behave specially

class A
{
  typedef int type;

  friend void function() { 
    type foo; /* type is visible */ 
  };
};

If you had defined "function" in the namespace scope, then "type" would not be visible - you would have to say "A::type". That's why it says in the next sentence "A friend function defined outside the class is not.". Unqualified name lookup for an in-class definition is stated as

Name lookup for a name used in the definition of a friend function (11.4) defined inline in the class granting friendship shall proceed as described for lookup in member function definitions. If the friend function is not defined in the class granting friendship, name lookup in the friend function definition shall proceed as described for lookup in namespace member function definitions.

So the text you quoted is not really required to be normative - the specification of unqualified name-lookup already covers it.

这篇关于GCC中的朋友功能范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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