编程语言
首页 > 编程语言> > C++翁恺学习17-const

C++翁恺学习17-const

作者:互联网

const

constants

compile time constants

const int bufsize = 1024;
enxtern const int bufsize;

run-time constants

const int class_size = 12;
int finalGrade[class_size];//ok

int x;
cin>>x;
const int size = x;
double classAverage[size];//error

编译器不知道x的值,因为编译器不知道需要分配内存的大小。

pointer and const

char *const q = "abc";//q is const
*q = "c"//ok
q++;//error   指针是const 

const char *p = "abcd";//(*p) is a cosnt char   
*p = "b";//error 指针指的内存的东西是 const
p++; // ok 下一个内存的东西也是 const 了

quiz: what do these mean?

cosnt person* p = &p1; // 对象是 const
person const* = &p1;   // 对象是 const
person *const p= &p1; // 指针是 const

*的前面还是后面。 * 在 const 前, 指针是 const; * 在 const 后,对象是 const

pointers and constants

int i;const int ci=3;
int *ip;ip=&i;ip = &ci;  //error
const int *cip; 对象是 constcip=&i;cip = &ci;

string literals 字符串常量

char* s = "hello,world";

if you want to change the string ,put it in an array:

char s[] = "hello,world!"; // 数组在

C++中三种内存模型:

本地变量,在中;

全局变量在全局数据区里,全局变量中的这种常量(“hello,world”)在代码段里,代码段不可写的

new出来的东西在中;

conversions

passing by const value

void f1(const int i){
    i++;//illegal -- compile-time error
}

returning by const value?

int f3(){return 1;}
const int f4(){return 1;}
int main(){
    const int j = f3();//work fine
    int k = f4(); //but this works fine too
}

passing and returning addresses

constant objects

const member functions

const member function usage

 

constant in class

class A{
    const int i;
};

compile-time constants in classes

class HasArray{
    const int size;
    int array[size]; //error,不能作为数组的大小, 1.使用static  2. 枚举
    ...
}

​​​

标签:const,17,int,error,ok,翁恺,day,size
来源: https://blog.csdn.net/hymn1993/article/details/122808885