【发布时间】:2017-12-22 22:41:17
【问题描述】:
请在这个问题中假设 gcc 7.2.1 的版本
我想声明一个行为类似于 const 的全局变量,但是在程序执行之前无法检测到初始化它的值。换句话说,目标变量将在第一次分配后重新分配。
这个概念的一个丑陋的方法如下:
#include<iostream>
int numberOfPeople; //Do not re-assign it after it first assign
int main(){
std::cin >> numberOfPeople; // Do not re-assign numberOfPeople since then !!!
// Following of codes omitted.
}
如您所见,这是一种非常丑陋的方法,编译器无法检查。我想知道 C++ 中是否有一种表示法可以冻结变量,因为它第一次分配。
所以我可以这样写代码:
#include<iostream>
magic_notation int numberOfPeople;
int main(){
std::cin >> numberOfPeople; // Allowed as it's first assign.
// Median codes omitted.
numberOfPeople = 60. //Disallowed and will get an error message from compiler!
// Following codes omitted.
}
在上面的 c++ 代码中,有没有可以像 magic_notation 这样使用的符号?
【问题讨论】:
-
使其成为控制访问的类的成员。
-
@neil-butterworth 感谢您的回复。但是,你能给我一个示例代码吗?
-
我想你正在寻找这个:stackoverflow.com/questions/35800643/…
-
@EIjay 感谢您的回复。这是相似的。但是,我想找到一个基于语法的解决方案。
-
@TJM • 我认为您不会得到您所要求的编译时错误。它可以默默地忽略后续分配,或者在后续分配中抛出异常。
标签: c++