扫码关注官方订阅号
不具名命名空间不可以放在.h,可以举个例子为什么不可以么?我想来想去没找到例子。
关键看怎么用,在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: 0x602200 val: 0 addr: 0x602208 one has type: N12_GLOBAL__N_19TestClassE two has type: N12_GLOBAL__N_19TestClassE
稍微详细点,看这里 : https://zsounder.github.io/20...。
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
扫描下载App
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
关键看怎么用,在unnamed namespace中放什么东西,一个例子,如果放变量,就有问题了。
输出为:
稍微详细点,看这里 : https://zsounder.github.io/20...。