#include<iostream>
#include<string>
using namespace std;
void print(const string& str, int data) {
cout << str << " = " << data << endl;
}
void print(const string& str, double data) {
cout << str << " = " << data << endl;
}
int main () {
const int bufSize = 1024;
//bufSize = 512; //const 不可修改
print("bufSize", bufSize);
// 指向常量的指针
const double pi = 3.14;
//double* ptr = π //const 修饰的对象需要使用const指针
const double* cptr = π
print("pi", *cptr);
double tmpVal = 1.57;
cptr = &tmpVal;
print("tmpVal", *cptr);
//*cptr = 3.15; // 常指针可以指向普通变量,但是不能通过常指针修改变量。
// const 指针
int errNumb = 0;
int * const curErr = &errNumb; //curErr将一直指向errNumb
print("errNumb", *curErr);
*curErr = 100;
print("errNumb", *curErr);
// 顶层const,底层const
int i = 0;
int * const p1 = &i; // 不能改变p1的值,这是一个顶层const
const int ci = 42; // 不能改变ci的值,这是一个顶层const
const int* p2 = &ci; // 允许改变p2的值,这是一个底层const
const int* const p3 = p2; // 靠右的const是顶层const,靠左的是底层const
const int &r = ci; // 用于声明引用的const都是底层const
//当执行拷贝操作时,常量是顶层const还是底层const区别明显,其中顶层const不受影响。
i = ci; // 正确:拷贝ci的值,ci是一个顶层const,对此操作无影响
p2 = p3; // 正确:p2和p3指向的对象类型相同,p3顶层const的部分不受影响
// 底层const的限制,执行对象拷贝时,拷入和拷出的对象必须具有相同底层const资格,
// 或者两个对象的数据类型能够转换。一般,非常量可以转换成常量,反之则不行。
//int* p = p3; // 错误:p3包含底层const的定义,而p没有
p2 = p3; // 正确:p2 和 p3都是底层const
p2 = &i; // 正确:int* 能够转换成const int*
// int& r = ci; // 错误:错误,普通的int& 不能绑定到int常量上
const int& r2 = i; // 正确:const int& 可以绑定到一个普通int上
// p3既是顶层const也是底层const,拷贝p3时可以不用在乎它是一个顶层const,
// 但是必须清楚它指向的对象得是一个常量。因此,不能用p3去初始化p,因为p
// 指向的是一个普通(非常量)的整数。另一方面,p3的值可以赋给p2,因为这
// 两个指针都是底层const,尽管p3同时也是一个常量指针(顶层const),仅就
// 这次赋值而言不会有什么影响。
return 0;
}
C++ —— const 限定符
猜你喜欢
转载自blog.csdn.net/Lynn_mg/article/details/89536969
今日推荐
周排行