C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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,它将编译并正确运行.

我失踪了什么

我看了相关的话题,但找不到符合我问题的东西.

> C++: namespace conflict between extern “C” and class member
> Why this friend function can’t access a private member of the class?

感谢人.

编辑:

我现在相信外部的“C”与这个问题无关.
请忽略它.

解决方法

我不知道这个解释,但是如果你把foo()放在一个命名空间中,它就可以工作.
#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”的朋友不能达到名字空间的私人会员全部内容,希望文章能够帮你解决C全球外部“C”的朋友不能达到名字空间的私人会员所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。