Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Namespace có thể lồng nhau trong C++ không?

Có, namespace có thể lồng nhau (nested) trong C++. Chúng ta có thể định nghĩa một namespace bên trong namespace khác như sau:

Cú pháp

namespace namespace_name1 {
    // khai báo code
    namespace namespace_name2 {
        // khai báo code
    }
}

Bạn có thể truy cập thành viên của namespace lồng nhau bằng toán tử phạm vi (resolution operator) như sau:

// truy cập thành viên namespace_name2
using namespace namespace_name1::namespace_name2;
// truy cập thành viên namespace_name1
using namespace namespace_name1;

Ví dụ

#include <iostream>
using namespace std;

// namespace đầu tiên
namespace first_space {
    void func() {
        cout << "Bên trong first_space" << endl;
    }
    // namespace thứ hai
    namespace second_space {
        void func() {
            cout << "Bên trong second_space" << endl;
        }
    }
}
using namespace first_space::second_space;

int main() {
    // Gọi hàm từ namespace thứ hai.
    func();
    return 0;
}

Kết quả

Bên trong second_space