简体   繁体   English

为什么我不能使用static_cast <const char**> (str)而不是(const char **)str?

[英]Why cant i use static_cast<const char**>(str) instead of (const char**)str?

I have an issue, it doesn't want to cast using static_cast<> . 我有一个问题,它不想使用static_cast <>进行转换 What can it be? 会是什么

void myCompare(const void *str)
{
    const char *ca = *(static_cast<const char**>(str)); //error
    const char *a = *(const char **)str; //ok
}

You're casting away const on the second level, which static_cast is not allowed to do (in fact, no "C++" cast apart from const_cast ): 您在第二个级别上抛弃了const ,这是不允许static_cast进行的(实际上,除了const_cast之外,没有“ C ++” static_cast const_cast ):

          void    const*
   char const*         *
// ^^^^^^^^^^^    ^^^^^
// pointee        cv-qualifiers
//                of pointee

Instead, write 相反,写

const char *ca = *(static_cast<const char* const*>(str));

The (char const**) cast works here because it is equivalent to a static_cast followed by a const_cast (as per [expr.cast]/(4.3)) - ie it was equivalent to (char const**) static_cast const_cast在这里起作用,因为它等效于static_cast后跟const_cast (根据[expr.cast] /(4.3))-即它等效于

const char *ca = *(const_cast<const char**>(static_cast<const char* const*>(str)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么不strlen(..)期望const char * const str而不是const char * - why doesn't strlen (..) expect const char* const str instead of const char* 不允许从&#39;const unsigned char * const *&#39;到&#39;const char * const *&#39;的static_cast - static_cast from 'const unsigned char *const *' to 'const char *const *' is not allowed 尝试将static_cast &lt;&gt; const char []转换为无符号字符时出错* - Error when attempting to static_cast<> const char[] to unsigned char * 在Effective C ++ Item 3中,为什么要使用static_cast <const TextBlock&> (* this)而不是static_cast <const TextBlock> (*这个)? - In Effective C++ Item 3,why use static_cast<const TextBlock&>(*this) instead of static_cast<const TextBlock>(*this)? 不允许从 &#39;const char *&#39; 到 &#39;void *&#39; 的 static_cast - static_cast from 'const char *' to 'void *' is not allowed 为什么我可以对static * cast使用void *但不能对char *使用 - Why can I use static_cast With void* but not With char* 为什么不能在const char * str上应用str.find_last_of() - Why not able to apply str.find_last_of( ) on const char * str &#39;char const * str&#39;作为模板参数 - 'char const *str' as template argument str::find() function 用于 const char* - str::find() function for the const char* 为什么static_cast不使用转换运算符指向const? - Why does static_cast not use the conversion operator to pointer to const?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM