小编osd*_*kid的帖子

C++ Namespace成员访问不同的文件如何?"namespace std"如何实现?

我在sample.h中声明了以下命名空间

// namespace with identifier
namespace N1
{
    int b = 80;
}
Run Code Online (Sandbox Code Playgroud)

sample1.cpp使用上面的命名空间声明

#include <iostream>
#include "sample.h"

using namespace std;
using namespace N1;

int main(void)
{
    cout << "b (in main) = " << b << endl;
      foo(); //written in sample2.cpp
      return 0;
}
Run Code Online (Sandbox Code Playgroud)

sample2.cpp还使用sample.h中声明的命名空间

#include <iostream>
#include "sample.h"

using namespace std;
using namespace N1;

void foo(void)
{
    cout << "b = " << b << endl;
}
Run Code Online (Sandbox Code Playgroud)

当我编译时,我得到了以下错误

$> g++ sample1.cpp sample2.cpp
/tmp/ccB25lEF.o:(.data+0x0): multiple definition of `N1::b'
/tmp/cchLecEj.o:(.data+0x0): …
Run Code Online (Sandbox Code Playgroud)

c++ namespaces

3
推荐指数
2
解决办法
9208
查看次数

标签 统计

c++ ×1

namespaces ×1