【发布时间】:2012-01-02 16:55:36
【问题描述】:
在搜索了 SO 之后,一个问题告诉我,内联友元函数的 词法 范围是它定义的类,这意味着它可以访问例如班级中的typedefs 没有限定他们。但后来我想知道这种函数的实际作用域是什么? GCC 至少拒绝了我调用它的所有尝试。可以通过 ADL 以外的方式调用示例中的函数吗?由于没有参数,这在此处是不可能的?
感谢标准报价,因为我目前无法访问我的副本。
namespace foo{
struct bar{
friend void baz(){}
void call_friend();
};
}
int main(){
foo::baz(); // can't access through enclosing scope of the class
foo::bar::baz(); // can't access through class scope
}
namespace foo{
void bar::call_friend(){
baz(); // can't access through member function
}
}
导致这些错误:
prog.cpp: In function ‘int main()’:
prog.cpp:9: error: ‘baz’ is not a member of ‘foo’
prog.cpp:10: error: ‘baz’ is not a member of ‘foo::bar’
prog.cpp: In member function ‘void foo::bar::call_friend()’:
prog.cpp:15: error: ‘baz’ was not declared in this scope
【问题讨论】:
-
最好在你的问题中加入一些代码,而不是链接中的所有内容。
-
@iammilind:哎呀,我的意思是,不知何故忘记了...编辑。
-
11.3.7 说“在类中定义的友元函数在定义它的类的(词法)范围内。”
-
在 C++ 中的朋友可以访问您的私人会员。
-
@Cat:这就是我对第一部分的引用,关于访问 typedef。但这并不适用于真正的范围,否则我应该能够使用 try #2 访问它...