代码之家  ›  专栏  ›  技术社区  ›  johnnyodonnell

是否可以#将一个名称空间的类包含到另一个名称空间中

  •  0
  • johnnyodonnell  · 技术社区  · 6 年前

    #include

    namespace V3 {
        class C {
            public:
                void print();
        };
    }
    

    //V3。cpp

    #include <iostream>
    #include "V3.h"
    
    using namespace std;
    
    namespace V3 {
        void C::print() {
            cout << "Hello from C" << endl;
        }
    }
    

    //受欢迎。H

    namespace Popular {
        #include "V3.h"
    }
    

    //梅因。cpp

    #include "Popular.h"
    
    int main() {
        Popular::V3::C c;
        c.print();
    }
    

    $ g++ main.cpp V3.cpp
    /tmp/ccAVnUZi.o: In function `main':
    main.cpp:(.text+0x1f): undefined reference to `Popular::V3::C::print()'
    collect2: error: ld returned 1 exit status
    

    因此,我想知道,是否有可能 #包括 将命名空间的类转换为另一个命名空间?还是因为其他原因我没能复制这个例子?我在后面的一节(15.2.5)中读到,这可能是不可能的。

    0 回复  |  直到 6 年前
        1
  •  1
  •   Barry    6 年前

    #include Popular.h 是:

    namespace Popular {
        namespace V3 {
            class C {
                public:
                    void print();
            };
        }
    }
    

    这是合法的C++代码,当然有很多情况下它不会。

    C ::Popular::V3::C .该类型与中声明的类型不同且不相关 V3.h ::V3::C .第二种类型对其 print() V3.cpp .

    但这不是问题所在 打印() ::Popular::V3::C::print() (这也是与 )这个函数在任何地方都没有定义。因此,结果是,你得到了一个 undefined reference -你需要为这件事添加一个定义。比如说:

    // Popular.cpp
    #include <iostream>
    void Popular::V3::C::print() {
        std::cout << "This is bad and I should feel bad about it. :-(" << std::endl;
    }
    

    #包括 namespace 除非你有强烈的理由这么做。您可以改为提供名称空间别名:

    #include "V3.h"
    namespace Popular {
        namespace V3 = ::V3;
    }
    

    这会让你仍然写作 Popular::V3::C ,它现在实际上与 ::V3::C

    或类型别名:

    #include "V3.h"
    namespace Popular {
        using C = ::V3::C;
    }
    

    再来一次 ::Popular::C .