现在的位置: 首页 > 综合 > 正文

c++中的const

2013年11月10日 ⁄ 综合 ⁄ 共 732字 ⁄ 字号 评论关闭
#include <iostream>
#include <cstdio>
using namespace std;

const int size = 100;

int main()
{
   // size = 10; //error: assignment of read-only variable 'size'
   // int *ptr_size = &size; //error: invalid conversion from 'const int*' to 'int*'|
   // *ptr_size = 10; //运行时,产生段错误

  /*
   int *ptr_size = dynamic_cast<int *> (&size);//error: cannot dynamic_cast '& size' (of type 'const int*') to type 'int*' (target is not pointer or reference to class)||
   if(ptr_size) {
        *ptr_size = 10;
        cout << size << endl;
   }
   */

    const int buf_size  = 100;
    char buf[buf_size];

    //buf_size = 10; //error: assignment of read-only variable 'buf_size'
    //int *p = &buf_size; //error: invalid conversion from 'const int*' to 'int*'
    //*p = 10;
    printf("buf_size = %d\n", buf_size);



    buf[0] = 'a';

    printf("Hello world!\n");

    int a = 10;
    int * const cp = &a;
    //++cp;
   // ++buf;

    int * p = cp;
    cout << *p << endl;


    return 0;
}

抱歉!评论已关闭.