C++ const_cast usage instead of C-style casts

后端 未结 4 1535
长情又很酷
长情又很酷 2021-01-17 23:51

Why is the following?:

  const int i0 = 5;
//int       i1 = const_cast(i0);       // compilation error
  int       i2 = (int)i0;                           


        
4条回答
  •  失恋的感觉
    2021-01-18 00:27

    For the first error. const_cast can only be used on pointer or reference types. "int" is neither. This may or may not be the C++ standard (couldn't find a good reference). But it is the case for certain implementations such as MS's C++ compiler.

    For the second error. const_cast can only be used to remove a const or volatile qualifier not add it.

    Reference: http://msdn.microsoft.com/en-us/library/bz6at95h(VS.80).aspx

提交回复
热议问题