在 c++ 中声明一个全局范围变量 const
Declare a global scope variable const in c++
在 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,这甚至可以保证是线程安全的。
不,这是不可能的。声明必须与定义位于同一范围内。否则,它不是同一个名称。
相关文章:
- 如何创建一个空的全局类并在启动时实例化它
- 全局变量 多读取器 一个写入器多线程安全?
- 如何声明一个可以在整个程序中使用的全局 2d 3d 4d .. 数组(堆版本)变量?
- 如何从另一个进程解开全局钩子?
- 包括一个类来定义全局变量参数 c++ :(
- C++:实现一个全局常量,其值由用户给出
- 越界成员函数定义是否需要一个完全限定的类名,直到全局范围
- 除了调用全局删除运算符之外,删除一个void指针还能做什么呢
- Qt C++创建一个所有类都可以访问的全局变量
- 为什么它无法在 c++ 中全局声明一个构建为 dll 文件的类?
- 我真的可以使用 Type 的每个声明创建一个全局变量吗?
- 我们应该全局声明一个向量还是在递归函数中传递它以减少内存使用
- C++ 给出编译器错误,将一个(静态)常量全局变量设置为另一个静态常量变量
- 访问另一个.cpp文件中的.cpp文件中定义的全局变量
- C++全局常量数组:是否保证合并(优化)到一个副本中
- C 和 C++ 标头:在另一个结构内定义全局结构
- 在QT GUI中创建一个全局对象
- Rcpp:从全局环境调用一个R函数,并在C++代码中使用它
- 为什么 std::get<T> for 'variant' 是一个全局函数?
- 编译器是否可以从全局变量中读取两次,而不是存储一个局部变量