c++ - 不具名命名空間不可以放在.h
phpcn_u1582
phpcn_u1582 2017-05-16 13:21:09
0
1
824

不具名命名空間不可以放在.h,可以舉例為什麼不行?
我想來想去沒找到例子。

phpcn_u1582
phpcn_u1582

全部回覆(1)
PHPzhong

關鍵看怎麼用,在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...。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!