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

Sử dụng namespace trong C++


Namespace trong C++ giúp phân biệt các hàm, lớp, biến trùng tên từ thư viện khác nhau. Định nghĩa namespace bằng từ khóa namespace.

Cú pháp

namespace namespace_name {
    // khai báo code
}

Gọi: name::code (code là biến hoặc hàm).

Ví dụ

#include <iostream>
using namespace std;

namespace first_space {
    void func() {
        cout << "Inside first_space" << endl;
    }
}
namespace second_space {
    void func() {
        cout << "Inside second_space" << endl;
    }
}

int main() {
    first_space::func();
    second_space::func();
    return 0;
}

Kết quả

Inside first_space
Inside second_space