命名空间中的类朋友功能 [英] class friend function inside a namespace

查看:77
本文介绍了命名空间中的类朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图像这样在名称空间之外定义类朋友函数:

Im trying to define a class friend function outside the namespace like this:

namespace A{
class window{
    private:
    int a;
    friend void f(window);
};
}

 void f(A::window rhs){
 cout << rhs.a << endl;
}

我收到一个错误,说有歧义.并且有两个候选void A::f(A::window);void f(A::window).所以我的问题是:

Im getting an error said that there is ambiguity. and there is two candidates void A::f(A::window); and void f(A::window). So my question is :

1)如何使全局函数void f(A::window rhs)成为类A :: window的朋友.

1) How to make the global function void f(A::window rhs) a friend of the class A::window.

(阅读答案后)

2)为什么我需要通过执行::f(window)将窗口类内部的成员函数f限定为全局变量?

2) why do I need to qualify the member function f inside window class to be global by doing ::f(window) ?

3)在这种特殊情况下,为什么我需要预先声明函数f(A :: window),而当在命名空间中未定义类时,在将函数声明为a之后对函数进行声明是可以的朋友.

3) why do I need to predeclare the function f(A::window) in this particular case, whereas when the class is not a defined inside a namespace it's okey for the function to be declared after the function is declared a friend.

推荐答案

除了添加::之外,您还需要向前声明它,例如:

As well as adding a :: you need to forward declare it, e.g.:

namespace A { class window; }

void f(A::window);

namespace A{
  class window{
    private:
    int a;
    friend void ::f(window);
  };
}

void f(A::window rhs){
  std::cout << rhs.a << std::endl;
}

请注意,要使此前向声明起作用,您还需要前向声明类!

Note that for this forward declaration to work you need to forward declare the class too!

这篇关于命名空间中的类朋友功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆