C++如何在另一个名称空间中定义友元函数

gmxoilav  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(134)

我有一个类声明与此类似;

  1. #include "other.h"
  2. class A{
  3. public:
  4. A(){};
  5. private:
  6. friend Data someNamespace::function(A* elem);
  7. }

现在在另一个头文件中我有

  1. //other.h
  2. #include "A.h"
  3. namespace someNamespace {
  4. Data function(A* elem);
  5. }

ANd .cpp文件

  1. //other.cpp
  2. #include "other.h"
  3. Data someNamespace::function(A* elem){
  4. // do something here
  5. }

我不知道如何使名称空间作为第一个类的朋友。名称空间中的函数不能访问类A的私有值。我错过了什么?

zvokhttg

zvokhttg1#

有个办法前向声明class A,这样就可以在命名空间中声明Data function(A* elem),这样就可以在类A中命名someNamespace::function

  1. struct Data {};
  2. class A; // <-- *** You need this ***
  3. namespace someNamespace {
  4. Data function(A* elem);
  5. }
  6. class A {
  7. friend Data someNamespace::function(A* elem);
  8. };
  9. Data someNamespace::function(A* elem) {
  10. return Data();
  11. }

如果是多个文件

如果代码出现在单独的文件中,那么可以想象一个other.h文件如下所示:

  1. #include "data.h" // for the definition of `Data`
  2. class A; // so that `A*` makes sense
  3. namespace someNamespace {
  4. Data function(A* elem);
  5. }
  6. #include "A.h" // If the rest of the definition of `A` is needed.
  7. // "Include what you use" principle.
  8. // remaining "other" declarations here
展开查看全部

相关问题