码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 基本使用

时间:2015-05-30 15:16:36      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

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 *

c++ 基本使用

标签:

原文地址:http://www.cnblogs.com/asnjudy/p/4540374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!