c++ - 不具名命名空间不可以放在.h

【字号: 日期:2023-03-21浏览:23作者:雯心

问题描述

不具名命名空间不可以放在.h,可以举个例子为什么不可以么?我想来想去没找到例子。

问题解答

回答1:

关键看怎么用,在unnamed namespace中放什么东西,一个例子,如果放变量,就有问题了。

//one.h#include <iostream>#include <typeinfo>namespace {class TestClass {};int i;}const std::type_info& one_get_TestClass_Info();const std::type_info& two_get_TestClass_Info();//one.cpp#include 'one.h'const std::type_info& one_get_TestClass_Info(){ i = 10; std::cout << 'val: ' << i << ' addr: ' << &i << std::endl; return typeid(TestClass);}//two.cpp#include 'one.h'#include <iostream>#include <typeinfo>using namespace std;const std::type_info& two_get_TestClass_Info(){ std::cout << 'val: ' << i << ' addr: ' << &i << std::endl; return typeid(TestClass);}//main.cpp#include 'one.h'using namespace std;int main(){ const std::type_info& t1 = one_get_TestClass_Info(); const std::type_info& t2 = two_get_TestClass_Info(); std::cout << 'one has type: ' << t1.name() << ’n’ << 'two has type: ' << t2.name() << ’n’; if (t1 == t2) {cout << 'same type'; } return 0;}

输出为:

val: 10 addr: 0x602200val: 0 addr: 0x602208one has type: N12_GLOBAL__N_19TestClassEtwo has type: N12_GLOBAL__N_19TestClassE

稍微详细点,看这里 : https://zsounder.github.io/20...。

相关文章: