跨不同命名空间的友元类不起作用,并且无法识别命名空间
Friend classes across different namespaces not working and namespace is not recognized
我在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
中声明一个新类一样,但在另一个文件中,我将MeshNamespace
和ReferenceElementNamespace
与using
一起使用,这让我感到不明确。尽管如此,这并不能解决任何问题
我所知道的:
- 支持(其他(命名空间中的正向声明
- 不支持嵌套类的正向声明
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上演示
- 命名空间中具有.h和.cpp文件的类
- 从父命名空间重载类型
- 在命名空间中定义函数还是限定函数
- C++:对不存在的命名空间使用命名空间指令
- 通过继承类使用来自不同命名空间的运算符
- 使用命名空间时出现多个定义错误
- CUDA内核和数学函数的显式命名空间
- 嵌套的匿名命名空间
- CMakeLists.txt中的命名空间表示法
- 类是C++中的命名空间吗
- 在命名空间中使用全局命名空间中的函数
- 如何使 std::sort 在 std::swap 和我的命名空间的模板化交换之间没有名称冲突?
- 命名空间 pqxx 无法识别 - 将 libpqxx 添加到 Windows 上的 Visual Studio Post
- 无法识别命名空间名称
- 获取 VC 对话编辑器以识别命名空间中的对话类
- 来自单独.cpp文件中同一命名空间的 free 函数,C++ 中无法识别
- Eclipse CDT 项目与犰狳 - CDT 无法识别'arma'命名空间
- 函数未被识别为命名空间的一部分
- 链接器是否识别命名空间别名
- Eclipse CDT插件无法识别某些文件中的std命名空间