【问题标题】:why can I still give const value a new value为什么我仍然可以给 const 值一个新值
【发布时间】:2021-07-24 21:13:45
【问题描述】:

书上说我给了一个数字就不能改变const的值,但是好像给了一个数字还是可以的。

#include<iostream>
using namespace std;
const int fansc(100);
cout<< fansc << endl; //output:100
int fansc(20);
cout<< fansc << endl;//output:20

【问题讨论】:

  • 此代码无法编译,这意味着它不是您正在运行的代码。请发minimal reproducible example
  • 无法重现:godbolt.org/z/KWh7s1nzh
  • 哦,你根本没有使用编译器。您似乎正在使用一些解释器。您可以编辑您的问题以包含这些详细信息,但我会强烈建议使用实际的编译器。正如您在代码中所展示的那样,解释器允许您执行无效的 C++ 操作。
  • 因为增量编译器的原因,有问题的代码大概是这样的:godbolt.org/z/TYasnYWzh
  • “这本书” -- 哪本书?这本书是否涵盖了蟒蛇?如果它仅涵盖常规 C++,那么它不适用于您的情况。 (例如,常规 C++ 会要求行 cout&lt;&lt; fansc &lt;&lt; endl; 位于函数内部。您的行不是。)

标签: c++ constants jupyter xeus-cling


【解决方案1】:

您提供的 C++ 代码无法编译,这是正确的。 const variable(a) 是,嗯,... 常数。错误显示在以下程序和脚本中:

#include <iostream>
using namespace std;
int main() {
    const int fansc(100);
    cout << fansc << endl;
    int fansc(20);
    cout << fansc << endl;
}
pax> g++ --std=c++17 -Wall -Wextra -Wpedantic -o prog prog.cpp
prog.cpp: In function ‘int main()’:
prog.cpp:6:9: error: conflicting declaration ‘int fansc’
    6 |     int fansc(20);
      |         ^~~~~
prog.cpp:4:15: note: previous declaration as ‘const int fansc’
    4 |     const int fansc(100);
      |               ^~~~~

这留下了您在评论中提到的 Anaconda 位。我对此几乎没有经验,但在我看来,唯一可行的方法是,如果第二个 fansc 定义以某种方式在与第一个不同的 范围 中创建。在真正的 C++ 代码中,会是这样的:

#include <iostream>
using namespace std;
int main() {
    const int fansc(100);
    cout << fansc << endl;
    { // new scope here
        int fansc(20);
        cout << fansc << endl;
    } // and ends here
    cout << fansc << endl;
}

然后输出是:

pax> g++ --std=c++17 -Wall -Wextra -Wpedantic -o prog prog.cpp && ./prog
100
20
100

(a) 是的,我知道这是自相矛盾的:-)

【讨论】:

  • 第二个代码是否意味着您使用大括号 make "int fan(20)" 作为块。一旦出块,fansc(20)就会被销毁,fansc的值为100。
  • @ryw:是的,“20”fansc 只能在其范围内访问,该范围由内大括号限定。在内部右大括号之后,标识符fansc 的任何使用都将引用“100”变体。我已经调整了第二个代码 sn-p 来显示这个。
  • 次要注意,但这与 Anaconda 或 Conda 本身无关。问题更多是关于 Jupyter 和(大概)xeus-cling C++ kernel 被用作解释器。
  • @ryw:更清晰:第二个代码打开了一个新范围,允许它创建第二个全新变量,该变量也恰好命名为 fans。在这个新范围内,名称 fans 现在指的是第二个变量而不是第一个变量
猜你喜欢
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
  • 2020-07-28
  • 1970-01-01
相关资源
最近更新 更多