本文介绍了GCC中的朋友功能范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 根据标准: 那么为什么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。这就是为什么它在下一句中说:在课堂外定义的朋友功能不是。。名称定义中的非限定名称查找称为 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.cpptest.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 speciallyclass 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 So the text you quoted is not really required to be normative - the specification of unqualified name-lookup already covers it. 这篇关于GCC中的朋友功能范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!