命名空间中的类朋友功能

编程入门 行业动态 更新时间:2024-10-28 18:26:57
本文介绍了命名空间中的类朋友功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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!

更多推荐

命名空间中的类朋友功能

本文发布于:2023-11-09 14:55:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572661.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能   朋友   空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!