不具名命名空間不可以放在.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...。
關鍵看怎麼用,在unnamed namespace中放什麼東西,一個例子,如果放變量,就有問題了。
輸出為:
稍微詳細點,看這裡 : https://zsounder.github.io/20...。