【发布时间】:2021-05-17 05:13:36
【问题描述】:
我在使用 C++ 中的朋友类时遇到问题
我正在向前声明朋友类并使用适当的名称空间,所以我不知道发生了什么。
内部类 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 中声明一个新类,但后来我在另一个我使用的文件中变得模棱两可MeshNamespace 和 ReferenceElementNamespace 与 using。但这并不能解决任何问题
【问题讨论】:
-
您是否尝试过在命名空间中进行前向声明?例如。
namespace MeshNamespace { class Mesh; }我已经习惯了不支持嵌套类的前向声明这一事实。您可能指的是命名空间中的一个类,但我不确定编译器是否也这样认为。 -
顺便说一句。你混合了
MeshNamespace和MeshNameSpace。 -
使用
namespace MeshNamespace { class Mesh; },我得到了编译:Demo on coliru -
@Scheff 成功了!非常感谢。我在
ReferenceElement.hpp中的namespace ReferenceElementNamespace {之前添加了namespace MeshNamespace { class Mesh; },这解决了所有问题。如果你想写,我很乐意接受你的回答 -
@Scheff 你的第二条评论是什么意思?