在 c++ 中声明一个全局范围变量 const

Declare a global scope variable const in c++

本文关键字:全局 一个 范围 变量 const c++ 声明      更新时间:2023-10-16

在 C 或 C++ 中,是否可以声明具有全局范围的 const,但定义是在函数内部设置的?

做类似的事情怎么样(实时样本)

const int& MyConstValue(int x) {
    static const int myConstValue = x;
    return myConstValue;
}
int main() {
    std::cout << MyConstValue(5) << std::endl; // This is the 1st call and "wins"
    std::cout << MyConstValue(8) << std::endl;
    return 0;
}

输出为

5
5

至少对于 c++11,这甚至可以保证是线程安全的。

不,这是不可能的。声明必须与定义位于同一范围内。否则,它不是同一个名称。