本文介绍了C ++全局外部“C”朋友不能到达命名空间类的私有成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑代码:
#include <iostream>
using namespace std;
extern "C"
void foo( void );
namespace A
{
template< int No >
class Bar
{
private:
friend void ::foo( void );
static void private_func( int n );
};
template< int No >
void Bar< No >::private_func( int n )
{
cout << "A:Bar< " << No << ">::private_func( " << n << " )" << endl;
}
}
extern "C"
void foo( void )
{
A::Bar< 0 >::private_func( 1 );
}
int main( )
{
cout << " ---- " << endl;
foo( );
}
G ++提供:
> g++ -Wall -o extern_c extern_c.cpp
extern_c.cpp: In function ‘void foo()’:
extern_c.cpp:20:7: error: ‘static void A::Bar<No>::private_func(int) [with int No = 0]’ is private
extern_c.cpp:29:31: error: within this context
如果我评论 namspace A
,它将正确编译并运行。
If I comment the namspace A
, it will compile and run correctly.
我缺少什么?
我看了相关的主题,但找不到任何适合我的问题。
I looked related topics, but could not find any that fits in my problem.
- C++: namespace conflict between extern "C" and class member
- Why this friend function can't access a private member of the class?
感谢他人。
编辑:
现在确信 externC
与问题无关。
请忽略它。
I am now convinced that extern "C"
has nothing to do with the problem.Please ignore it.
推荐答案
我不知道解释,但如果你把 foo )到命名空间中。
I don't know the explanation, but if you put foo( ) into a namespace, it works.
#include <iostream>
using namespace std;
namespace C
{
extern "C"
void foo( void );
}
namespace A
{
template< int No >
class Bar
{
private:
friend void C::foo( void );
static void private_func( int n );
};
template< int No >
void Bar< No >::private_func( int n )
{
cout << "A::Bar< " << No << ">::private_func( " << n << " )" << endl;
}
}
namespace C
{
extern "C"
void foo( void )
{
A::Bar< 0 >::private_func( 1 );
}
}
int main( )
{
cout << " ---- " << endl;
C::foo( );
}
结果:
bbcaponi@bbcaponi friends]$ g++ -Wall namespace_friend.cpp -o namespace_friend
[bbcaponi@bbcaponi friends]$ ./namespace_friend
----
A::Bar< 0>::private_func( 1 )
这篇关于C ++全局外部“C”朋友不能到达命名空间类的私有成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!