開發環境 Qt Creator 4.8.2
編譯器版本 MinGw 32-bit
const_cast
用法:
const_cast<type_id> (expression)
說明:
該運算符用來修改類型的const或volatile屬性。除了const 或volatile修飾之外, type_id和expression的類型是一樣的。
常量指針被轉化成非常量指針,並且仍然指向原來的對象;常量引用被轉換成非常量引用,並且仍然指向原來的對象;常量對象被轉換成非常量對象。
如下代碼在Qt開發環境中報錯
template <typename elemType>
inline elemType* begin_(const vector<elemType> &vec)
{
return vec.empty() ? 0 : &vec[0];
}
error: cannot initialize return object of type 'int *' with an rvalue of type 'const __gnu_cxx::__alloc_traits<std::allocator<int> >::value_type *' (aka 'const int *')
將代碼修改后如下
/*
* 獲取vector的首地址
*/
template <typename elemType>
inline elemType* begin_(const vector<elemType> &vec)
{
return vec.empty() ? 0 : const_cast<elemType *>(&vec[0]);
}
參考資料:
1 https://www.cnblogs.com/chio/archive/2007/07/18/822389.html 【C++專題】static_cast, dynamic_cast, const_cast探討