使用static_cast将'int'转换为'const int',但既不初始化也不具有const行为

Har*_*aks 2 c++ const static-cast

我正在关注一个教程,它说我可以使用静态强制转换将非const变量设为const。我尝试这样做,但编译器每次都会给我一个错误。

#include <iostream>
using namespace std;

int main()
{
int j = 0;
static_cast<const int&>(j) = 5 ;

cout << j;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器给我以下错误消息。

hello.cpp: In function 'int main()':
hello.cpp:11:28: error: assignment of read-only location 'j'
 static_cast<const int&>(j) = 5 ;
Run Code Online (Sandbox Code Playgroud)

然后,我尝试查看“ j”是否变为常数。但是我可以为此赋值,编译器在那里没有显示任何问题。由于前一行中的问题,可能是编译器未编译该行。

#include <iostream>
using namespace std;

int main()
{
int j = 0;
static_cast<const int&>(j) = 5 ;
j = 8;

cout << j;
return 0;
}
Run Code Online (Sandbox Code Playgroud)

我已经搜索了很多解决方案,但没有找到任何解决方案。

J. *_*rez 5

常量与可变-哪个是变量?

变量就是定义时的含义。如果您写:

int j = 0; // j is a mutable int
Run Code Online (Sandbox Code Playgroud)

然后j是可变的int。这不会改变。如果你写

const int j = 0; // j is a constant int
Run Code Online (Sandbox Code Playgroud)

然后j是一个const int。写作

static_cast<const int&>(j)
Run Code Online (Sandbox Code Playgroud)

意思是“这个表达式的情况下,治疗j,就好像是const”。这意味着您无法更改它的值,因为它是const。

static_cast<const int&>(j) = 10; //Error: can't change the value of a const int
Run Code Online (Sandbox Code Playgroud)

哪里const有用?

const之所以有用,是因为它可以防止因意外更改某些内容而导致的错误。例如,我可以编写一个计算字符串中空格的函数:

int countSpaces(const std::string& s) {
    int count = 0; 
    for(char c : s) {
        if(c == ' ') count += 1;
    }
    return count; 
}. 
Run Code Online (Sandbox Code Playgroud)

在这里,我将参数作为const string&。这能达到什么目的?

  • 因为const std::string&是参考,所以我不必复制字符串(这会很昂贵)
  • 因为const std::string&是const,所以写的人countSpaces承诺countSpaces不会更改任何字符串。