Abh*_*yal 7 c++ static const c++11
在以下示例中 -
#include <iostream>
int someMethod(){
static int a = 20;
static const int result = a + 1;
++a;
std::cout << " [" << a << "] ";
return result;
}
int main(){
std::cout << someMethod() << "\n";
std::cout << someMethod() << "\n";
std::cout << someMethod() << "\n";
}
Run Code Online (Sandbox Code Playgroud)
输出如下 -
[21] 21
[22] 21
[23] 21
是什么原因result导致在对同一函数进行的后续调用中阻止修改值?我也打印了变量的输出a,这肯定是递增的,因为它是静态的,因此同一方法不能存在多个副本.
这里const只会扰乱读者的真正原因。这段代码的执行效果完全相同。
int someMethod(){
static int a = 20;
static int result = a + 1;
++a;
std::cout << " [" << a << "] ";
return result;
}
Run Code Online (Sandbox Code Playgroud)
真正的原因是=符号可以代表 C++ 中的两种不同操作:赋值(每次执行)或初始化(仅在创建变量时执行)。区别在于它是变量声明/定义的一部分。
在正常上下文中(不是块静态变量),两者是等效的,因为每次声明它的块运行时都会创建一个自动变量(或者至少编译器必须确保所有行为都像这种情况一样)。
但对于块静态变量来说,初始化只发生一次,这里变量结果被初始化为21,并且它的值永远不会改变。
这些变体会有很大不同
int someMethod(){
static int a = 20;
static int result;
result = a + 1; // assignation: result will see its value change with the value of a
...
int someMethod(){
static int a = 20;
static const int result = a;
result = a + 1; // Error modification of a const declared variable
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
375 次 |
| 最近记录: |