PHPz2017-05-16 13:23:09
關鍵看怎麼用,在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...。