gpt4 book ai didi

c++ - const_cast 是否返回尖括号内指定的类型

转载 作者:太空宇宙 更新时间:2023-11-04 15:39:16 26 4
gpt4 key购买 nike

我对 const_cast 的返回类型有点困惑?尖括号内的类型是否 <>是返回类型吗?

const int i = 5;
int b = const_cast<int&>(i);

const_cast返回 int& (整数引用),如果是,那么为什么我们如何将它存储为整数?或者我们应该将代码修改为:

const int i = 5; 
int & b = const_cast<int&>(i);

最佳答案

是的。但不是返回,您应该说结果表达式的类型 <> 中的类型.

当该类型是引用时,如 const_cast<int&> ,这意味着它是一个左值。在第一种情况下没有区别,因为无论如何它都会立即转换为右值。但是,const在这样的 r 值中被忽略,所以:

int b = const_cast<int&>(i); //ok
int b = const_cast<int>(i); //also ok
int b = i; //hey! also ok

第二种情况有所不同,因为没有左值到右值的转换:

int &b  = const_cast<int&>(i); //ok
int &b = const_cast<int>(i); //error: cannot bind a reference to an r-value
int &b = i; //error: cannot bind a `int&` to a `const int&`

关于c++ - const_cast 是否返回尖括号内指定的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26378539/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com