首页  >  问答  >  正文

c++ - 不具名命名空间不可以放在.h

不具名命名空间不可以放在.h,可以举个例子为什么不可以么?
我想来想去没找到例子。

phpcn_u1582phpcn_u15822736 天前881

全部回复(1)我来回复

  • PHPz

    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...。

    回复
    0
  • 取消回复