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

不具名命名空间不可以放在.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...。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板