【发布时间】:2014-10-31 15:23:02
【问题描述】:
我很难理解为什么以下 MWE 无法编译:
#include <iostream>
namespace N
{
class Foo
{
friend void bar( Foo& f );
void print(){ std::cout << "..." << std::endl; } // private by default
};
}
void bar( N::Foo& f )
{
f.print();
}
int main()
{
}
g++ 4.8.2 错误
Test.cpp: In function ‘void bar(N::Foo&)’:
Test.cpp:8:8: error: ‘void N::Foo::print()’ is private
void print(){ std::cout << "..." << std::endl; } // private by default
^
Test.cpp:14:10: error: within this context
我几乎肯定在这里遗漏了一些东西,但朋友函数bar() 可以访问类N::Foo 的任何私有成员。
注意:
- 将
bar()移动到命名空间N可解决此错误。 - 如果
::bar()不调用N::Foo::print(),则代码编译
为什么代码不能按原样编译?
编辑
再想一想,这个问题的标题并没有准确地描述问题。我会在适当的时候编辑它。
【问题讨论】:
-
为什么你认为这是一个错误? (我假设您故意说“错误”而不是“错误”。)
-
注意点。已编辑将“错误”一词替换为“错误”。
标签: c++ namespaces argument-dependent-lookup