c++ 基本使用

1 枚举

 1 enum ShapeType
 2 {
 3     circle,
 4     square,
 5     rectangle
 6 };
 7
 8 int main() {
 9
10     ShapeType shape = circle;
11
12     switch(shape)
13     {
14     case circle:
15         cout<<"ShapeType.circle"<<endl;
16         break;
17     case square:
18         cout<<"ShapeType.square"<<endl;
19         break;
20     case rectangle:
21         cout<<"ShapeType.rectangle"<<endl;
22         break;
23     default:
24         cout<<"Unknown!"<<endl;
25     }
26
27
28
29     return 0;
30 };

2. const_cast

    const int i = 0;

    /*
    error C2440: ‘const_cast‘ : cannot convert from ‘const int‘ to ‘int‘
    Conversion is a valid standard conversion, which can be performed implicitly or by use of static_cast, C-style cast or function-style cast
    转换是一个合法的标准转换,可以通过隐式执行,或使用static_cast、C风格的转换、函数式转换进行
    */

    //int j = const_cast<int>(i);

    /* 从 const int --> int, 下面4中都可以,唯独const_cast常量转换方式不行,只是因为它是一个合法的标准转换,用简单的方式已能处理还用不到高级的const_cast常量转换 */
    int j = i;        //隐式转换
    int h = static_cast<int>(i); //static_cast静态转换
    int k = (int)i;    //C风格转换
    int t = int(i);    //函数式转换

    /*
    const int * --> int *  使用const_cast常量转换
    */
    int* s = const_cast<int *>(&i);

    /*
    error C2440: ‘static_cast‘ : cannot convert from ‘const int *‘ to ‘int *‘
    Conversion loses qualifiers
    */
    int* w = static_cast<int *>(&i);

    //long* l = const_cast<long *>(&i);  // error C2440: ‘const_cast‘ : cannot convert from ‘const int *‘ to ‘long *‘

const_cast的用法:

  返回该常量对应的变量 = const_cast<该常量所属的类型>(常量)

转换的原则是:

  const int *  --> int *

时间: 2024-10-13 12:04:36