加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C全球外部“C”的朋友不能达到名字空间的私人会员

发布时间:2020-12-16 05:33:40 所属栏目:百科 来源:网络整理
导读:请考虑代码: #include iostreamusing 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
请考虑代码:
#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 )

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读