namespace 的使用

最近在看libzmq的源码,里面大量使用namespace。平时没怎么用过,故写一段测试代码作为笔记。

我抽象了一个客厅类 living_room_t,里面有chair_tdesk_t

CMakeLists

cmake_minimum_required(VERSION 3.3)
project(namespace_test)

set(SOURCE_FILES
main.cpp
living_room.hpp
living_room.cpp
chair.hpp
chair.cpp
desk.hpp
desk.cpp)

add_executable(home ${SOURCE_FILES})

源码

我使用的命名空间是homeliving_room_tchair_tdesk_t都属于同一个域home,但是属于不同的文件。有了共同的命名空间home,在living_room.hpp里头是不需要include chair.hppdesk.hpp 的。不过,在living_room.cpp中是需要include chair.hppdesk.hpp的。否则编译器就会报”allocation of incomplete type”的错误。

注意到在living_room.hpp里面有两个类声明class chair_t;class desk_t;,这样做的好处是后面的使用中不需要写home::chair_t *chair;,只需chair_t *chair;即可。

好了,Talk is cheap, show me the code.

头文件如下:

// living_room.hpp

namespace home
{
    class chair_t;
    class desk_t;

    class living_room_t
    {
        int id;
        int size;
        chair_t *chair;
        desk_t *desk;

    public:
        living_room_t(int id, int size = 10);            
        ~living_room_t();
        void prints();
    };
}
// chair.hpp
namespace home { 
    class chair_t {
        int id;

    public:
        chair_t(int id):
            id(id) 
        {}
        ~chair_t() {}
    };
}
// desk.hpp
namespace home {
    class desk_t {
        int id;
    public:
        desk_t(int id):
            id(id)
        {}
        ~desk_t() {}
    };
}

living_room的实现:

// living_room.cpp
#include <iostream>
#include "living_room.hpp"
#include "chair.hpp"
#include "desk.hpp"

home::living_room_t::living_room_t (int id, int size):
    id(id),
    size(size) 
{
    chair = new chair_t (1);
    desk = new desk_t (2);
}

home::living_room_t::~living_room_t() {
    delete chair;
    delete desk;
}

void home::living_room_t::prints()
{
    using namespace std;
    cout << "This is living room " << id << endl;
}

最后,主函数如下:

#include <iostream>
#include "living_room.hpp"

int main() {
    home::living_room_t living(1);
    living.prints();
    return 0;
}

你可能感兴趣的:(源码,namespace)