C++名称空间:交叉使用

And*_*w T 2 c++ namespaces include

请考虑以下示例.它由两个头文件组成,声明两个不同的名称空间:

// a1.h
#pragma once
#include "a2.h"

namespace a1 
{
    const int x = 10;
    typedef a2::C B;
}
Run Code Online (Sandbox Code Playgroud)

第二个是

// a2.h    
#pragma once
#include "a1.h"

namespace a2 {
  class C {
  public:
    int say() {
      return a1::x; 
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

还有一个源文件main.cpp:

#include <iostream>
#include "a1.h"
#include "a2.h"

int main()
{
  a2::C c;
  std::cout << c.say() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这样它就不会编译(尝试过GCC和MSVC).错误是a1未声明名称空间(Windows上为C2653).如果您以main.cpp这种方式更改包含订单:

#include "a2.h"
#include "a1.h"
Run Code Online (Sandbox Code Playgroud)

您会收到对称错误消息,即a2未声明命名空间.

有什么问题?

Gre*_*ers 11

您需要在头文件中使用前向声明,因为您有一个循环引用.像这样的东西:

// a1.h
#pragma once

namespace a2 {
    class C;
}

namespace a1 
{
    const int x = 10;
    typedef a2::C B;
}
Run Code Online (Sandbox Code Playgroud)