温馨提示×

C++中全局常量的访问权限如何设置

c++
小樊
82
2024-09-13 03:37:04
栏目: 编程语言

在 C++ 中,全局常量的访问权限与其他全局变量相同。默认情况下,它们具有外部链接,这意味着它们可以在定义它们的源文件之外的其他源文件中访问。

要将全局常量设置为只在定义它的源文件中访问,您需要使用 static 关键字。这将使其具有内部链接,从而限制其访问权限。

以下是一个示例:

// file1.cpp
#include <iostream>

// 全局常量,具有外部链接
const int global_constant = 42;

// 全局常量,具有内部链接
static const int static_global_constant = 100;

void print_constants() {
    std::cout << "global_constant: " << global_constant << std::endl;
    std::cout << "static_global_constant: " << static_global_constant << std::endl;
}
// file2.cpp
#include <iostream>

extern const int global_constant; // 声明外部链接的全局常量

int main() {
    std::cout << "global_constant in file2: " << global_constant << std::endl;

    // 下面的代码将导致编译错误,因为 static_global_constant 只能在 file1.cpp 中访问
    // std::cout << "static_global_constant in file2: " << static_global_constant << std::endl;

    return 0;
}

在这个例子中,global_constant 是一个具有外部链接的全局常量,可以在其他源文件中访问。而 static_global_constant 是一个具有内部链接的全局常量,只能在定义它的源文件(file1.cpp)中访问。

0