c – 与extern“C”函数的友谊似乎要求::限定名称
尝试使用一个extern“C”函数做一个类的朋友,这段代码的作用是:
#include <iostream> extern "C" { void foo(); } namespace { struct bar { // without :: this refuses to compile friend void ::foo(); bar() : v(666) {} private: int v; } inst; } int main() { foo(); } extern "C" { void foo() { std::cout << inst.v << std::endl; } } 但是我非常惊讶地发现,使用g 4.6.1和4.4.4我必须明确地写::在朋友void :: foo()中;否则友谊不行.这个::只有当它是extern“C”时才需要. 这是编译器bug /问题吗?我没想到这个行为. 我被困了这可能有一些规则,我找不到. 解决方法
最内围的命名空间是匿名的,你没有限定功能名称,所以the name is not found. 命名空间need not be anonymous,也可以. 请注意,问题中的外部“C”是一个红色的鲱鱼,如the following also fails for the same reason: void foo(); namespace { struct T { friend void foo(); private: void bar() { cout << "!"; } } t; } void foo() { t.bar(); } int main() { foo(); } /* In function 'void foo()': Line 7: error: 'void<unnamed>::T::bar()' is private compilation terminated due to -Wfatal-errors. */ [alternative testcase,adapted from your original code] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |