相关疑难解决方法(0)

为什么C++好友类只需要在其他命名空间中使用前向声明?

假设我有一个类F应该是类G(在全局命名空间中)和C(在命名空间中A)的朋友.

  • 要成为朋友A::C,F必须向前宣布.
  • 要成为朋友G,没有F必要的前瞻性声明.
  • 同样,一个班级A::BF可以成为朋友而A::C无需前瞻性声明

下面的代码说明了这一点,并使用GCC 4.5,VC++ 10以及至少与另一个编译器进行编译.

class G {
    friend class F;
    int g;
};

// without this forward declaration, F can't be friend to A::C
class F;

namespace A {

class C {
    friend class ::F;
    friend class BF;
    int c;
};

class BF {
public:
    BF() { c.c = 2; }
private:
    C c;
};

} // …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces friend forward-declaration

46
推荐指数
2
解决办法
3万
查看次数

如何在另一个C++命名空间中的全局命名空间中定义朋友?

我想在全局命名空间中定义二元运算符.运算符处理在另一个名称空间中定义的类,并且运算符应该可以访问该类的私有成员.我遇到的问题是,当我在类定义中将它作为朋友时,我不知道如何扩展该全局运算符的范围.

我尝试过类似的东西:

namespace NAME
{
    class A {
        public:
            friend A ::operator * (double lhs, const A& rhs);
        private:
            int private_var;
    };
}

A operator * (double lhs, const A& rhs)
{
    double x = rhs.private_var;
    ...
}
Run Code Online (Sandbox Code Playgroud)

编译器(g ++ 4.4)不知道如何处理它.看来就行了

friend A ::operator * ()
Run Code Online (Sandbox Code Playgroud)

被评估为(伪代码)

(A::operator)
Run Code Online (Sandbox Code Playgroud)

代替

(A) (::operator)
Run Code Online (Sandbox Code Playgroud)

如果我在运算符的声明中省略了::编译工作,但运算符在命名空间NAME中而不在全局命名空间中.

在这种情况下,如何限定全局命名空间?

c++ scope namespaces friend

13
推荐指数
2
解决办法
6900
查看次数

C++全局extern"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( …
Run Code Online (Sandbox Code Playgroud)

c++ templates namespaces extern

10
推荐指数
1
解决办法
1829
查看次数