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

问题描述 投票:2回答:2

我正在按照教程说它可以通过使用静态强制转换使非const变量成为const。我试着这样做,但编译器每次都给我一个错误。

#include <iostream>
using namespace std;

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

cout << j;
return 0;
}

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

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

然后我试着看看'j'是否变得不变。但我可以为此分配值,编译器在那里没有显示任何问题。由于前一行中的问题,可能是编译器不编译该行。

#include <iostream>
using namespace std;

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

cout << j;
return 0;
}

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

c++ const static-cast
2个回答
5
投票

Constant vs mutable - which one is a variable?

变量就是定义它时的变量。如果你写:

int j = 0; // j is a mutable int

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

const int j = 0; // j is a constant int

然后j是一个const int。写作

static_cast<const int&>(j)

意思是“在这个表达的背景下,将j视为const”。这意味着你不能改变它的值,因为它是常量。

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

Where is const useful?

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

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

在这里,我将参数作为const string&。这实现了什么?

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

1
投票

static_cast<const int&>(j)创建了对j的恒定引用。这是一个不能用于修改j的参考。因此,static_cast<const int&>(j) = 5无效,因为它试图通过该常量引用修改j

j的恒定引用的创建并没有使j本身成为一个常数。它只是在使用强制转换的表达式中表现为常量。除非你保持对j的恒定引用并从现在开始使用它,你仍然可以改变原始j的值。

© www.soinside.com 2019 - 2024. All rights reserved.