跨不同命名空间的友元类不起作用,并且无法识别命名空间



我在C中使用友元类时遇到问题++我正向声明friend类并使用适当的名称空间,所以我不知道发生了什么。在类MeshNamespace::Mesh中,ReferenceElementNamespace::ReferenceElement的成员仍然无法访问前者的私有成员。此外,在ReferenceElement.hpp中,MeshNamespace标识符不被识别。

如果我在没有命名空间的情况下将其转发声明为class Mesh;,它不会抱怨,但仍然不能工作,就像根本没有转发声明一样;

//文件ReferenceElement.hpp

namespace ReferenceElementNamespace {
class MeshNamespace::Mesh; // ReferenceElement.hpp:27:9: error: use of undeclared identifier 'MeshNamespace'
class ReferenceElement : public IReferenceElement 
{
private:
vector<Polygon> _referenceElementPolygons;   //(**)
friend class MeshNameSpace::Mesh; //ReferenceElement.hpp:45:20: error: use of undeclared identifier 'MeshNameSpace'
};
}

//文件Mesh.hpp

#include "Mesh.hpp"
using namespace ReferenceElementNamespace;
namespace MeshNamespace {
class Mesh : public IMesh{
someFunction(ReferenceElement& referenceElement)
{
ReferenceElement ref;
Polygon &polygon = ref._referenceElementPolygons[0];  //Mesh.cpp:216:32: error: '_referenceElementPolygons' is a private member of 'ReferenceElementNamespace::ReferenceElement'
ReferenceElement.hpp:34:23: note: declared private here   // in line (**)
}
};
}

编辑:顺便说一句,我意识到前向声明class Mesh;而不是class MeshNamespace::Mesh;会被接受,因为这就像在命名空间ReferenceElementNamespace中声明一个新类一样,但在另一个文件中,我将MeshNamespaceReferenceElementNamespaceusing一起使用,这让我感到不明确。尽管如此,这并不能解决任何问题

我所知道的:

  1. 支持(其他(命名空间中的正向声明
  2. 不支持嵌套类的正向声明

OP写入:

class MeshNamespace::Mesh;
class OtherClass {
friend class MeshNamespace::Mesh;
};

以在CCD_ 13中转发声明CCD_。

它也可以是class MeshNamespace { class Mesh { } },但这是嵌套类的前向声明(不支持(。

我不知道如何区分它,而且编译器似乎也不能区分它。然而,修复方法很简单:

namespace MeshNamespace {
class Mesh;
}
class OtherClass {
friend class MeshNamespace::Mesh;
};

在coliru上演示


注意:

由于C++17,允许嵌套的命名空间定义:
namespace X::Y { }被认为等于namespace X { namespace Y { } }

类定义似乎也是如此。因此,添加一个定义

class MeshNamespace::Mesh { };

在CCD_ 17已经被定义一次之后是可以的。(然而,在namespace MeshNamespace至少定义一次之前,这也是一个错误。(

在coliru上演示

最新更新