在 C++ 中将非 const 转换为 const
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5853833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
casting non const to const in c++
提问by kamikaze_pilot
I know that you can use const_cast
to cast a const
to a non-const
.
我知道您可以使用const_cast
将 aconst
转换为非const
.
But what should you use if you want to cast non-const
to const
?
但是,如果您想将 non- const
to 转换为 ,您应该使用什么const
?
采纳答案by Motti
const_cast
can be used in order remove oradd constness to an object. This can be useful when you want to call a specific overload.
const_cast
可用于为对象删除或添加常量。当您想要调用特定的重载时,这会很有用。
Contrived example:
人为的例子:
class foo {
int i;
public:
foo(int i) : i(i) { }
int bar() const {
return i;
}
int bar() { // not const
i++;
return const_cast<const foo*>(this)->bar();
}
};
回答by Scott Langham
STL since C++17 now provides std::as_const
for exactly this case.
从 C++17 开始的 STL 现在std::as_const
正好提供这种情况。
See: http://en.cppreference.com/w/cpp/utility/as_const
请参阅:http: //en.cppreference.com/w/cpp/utility/as_const
Use:
用:
CallFunc( as_const(variable) );
Instead of:
代替:
CallFunc( const_cast<const decltype(variable)>(variable) );
回答by Ozair Kafray
You don't need const_cast
to add const
ness:
您不需要const_cast
添加const
ness:
class C;
C c;
C const& const_c = c;
Please read through this question and answerfor details.
请通读此问题和答案以了解详细信息。
回答by Jerry Coffin
You can use a const_cast
if you want to, but it's not really needed -- non-const can be converted to const implicitly.
const_cast
如果您愿意,您可以使用 a ,但它并不是真正需要的——非常量可以隐式转换为 const。
回答by Guillaume07
You have an implicit conversion if you pass an non const argument to a function which has a const parameter
如果将非 const 参数传递给具有 const 参数的函数,则会进行隐式转换
回答by beduin
const_cast
can be used to add const
ness behavior too.
const_cast
也可用于添加const
ness 行为。
From cplusplus.com:
This type of casting manipulates the constness of an object, either to be set or to be removed.
这种类型的转换操纵对象的常量性,要么设置要么删除。