C++ 如何让一个类依赖于一个命名空间,而那个命名空间又依赖于该类?

标签 c++ class struct namespaces forward-declaration

所以我有一个类,其中包含一些成员变量,这些成员变量是在命名空间中定义的结构的实例,而同一命名空间中的函数有一个参数,该参数是指向上述类实例的指针。

这看起来像:

一些类.h

#ifndef SOME_CLASS_H
#define SOME_CLASS_H

include "SomeNamespace.h"

class SomeClass
{
private:
    SomeNamespace::SomeStructure instance1, instance2;

    ...

SomeNamespace.h

#ifndef SOME_NAMESPACE_H
#define SOME_NAMESPACE_H

#include "SomeClass.h"

namespace SomeNamespace
{
    namespace AnotherNamespace
    {
        void SomeFunction( SomeClass *pSomeClass );
    }

    struct SomeStructure
    {
        ...
    }
    ...

我收到的错误:

Error C2065 'SomeClass': undeclared identifier  
Error C2653 'SomeNamespace' : is not a class or namespace name

第一个错误与:

void SomeFunction( SomeClass *pSomeClass );

第二个错误涉及:

SomeNamespace::SomeStructure instance1, instance2;

我通过添加前向声明“class SomeClass;”修复了第一个错误到文件的顶部:

SomeNamespace.h

#ifndef SOME_NAMESPACE_H
#define SOME_NAMESPACE_H

#include "SomeClass.h"

class SomeClass;

namespace SomeNamespace
{
    namespace AnotherNamespace
    {
        void SomeFunction( SomeClass *pSomeClass );
    }

    struct SomeStructure
    {
        ...
    }
    ...

我试图修复错误二,对命名空间和结构做同样的事情:

一些类.h

#ifndef SOME_CLASS_H
#define SOME_CLASS_H

include "SomeNamespace.h"

namespace SomeNamespace
{
    struct SomeStructure;
}

class SomeClass
{
private:
    SomeNamespace::SomeStructure instance1, instance2;

    ...

对命名空间和其中的结构进行前向声明会给我这些错误:

'SomeClass::instance1' uses undefined struct 'SomeNamespace::SomeStructure'
'SomeClass::instance2' uses undefined struct 'SomeNamespace::SomeStructure'

我已经搜索过其他用户发布的这个问题,但我没有找到帖子。

如果有人对这个问题有疑问并且觉得他们需要给它打个差评,那么还请添加评论说明为什么这是一个糟糕的问题,以帮助我下次避免同样的错误。

提前感谢大家的帮助。

最佳答案

根据您向我们展示的内容,您只需要在 SomeNamespace.h 中对 SomeClass 进行前向声明,而不是完整的包含:

#ifndef SOME_NAMESPACE_H
#define SOME_NAMESPACE_H

// #include "SomeClass.h"  // << don't do this.

class SomeClass;

namespace SomeNamespace
{
    namespace AnotherNamespace
    {
        void SomeFunction( SomeClass *pSomeClass );
    }

以上是有效的,因为指向 SomeClass 的指针不需要知道任何关于 SomeClass 的信息,除了它是一个类。

关于C++ 如何让一个类依赖于一个命名空间,而那个命名空间又依赖于该类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38572609/

相关文章:

C++ 两个矩阵的乘法

c++ - 使用 Boost.Python 和静态库构建

java - 有没有办法将文件中的类实现到新文件中?

java - 如何在没有属性类的情况下拥有相同的程序,这里是 int 私有(private)计数器

c - 指向 volatile 结构的不透明指针

将十六进制数据从 C 转换为值

c++ - Win32 替代 pthread

c++ - 带前导零的数字的反转

jQuery 根据类取消选中单选按钮

c++ - struct function greater 在这段代码中是如何工作的?