const关键字

const关键字的用法

  const修饰的量是一个常量即不能修改的量
  const修饰的量在定义的时候必须进行初始化

const关键字修饰变量

#include <iostream>

using std::cout;
using std::endl;

int main()
{
  //const关键字修饰的变量称为常量
  //常量必须要进行初始化
  const int num = 10;
  cout << "num = " << num << endl;
  return 0;
}

常量的创建

#include <iostream>

// 除了使用const关键字修饰变量来创建常量,还可以通过宏定义的方式来创建常量
#define NUM 100

using std::cout;
using std::endl;

int main()
{
  const int num = 10;
  cout << "const常量 : " << num << endl;
  cout << "宏定义 : " << NUM << endl;
  return 0;
}
const常量与宏定义的区别
  - 编译器的处理方式不同
      宏定义是在预处理阶段展开,做字符串替换
      const常量发生在编译时
  - 类型和安全检查不同
      宏定义没有类型,不做任何类型检查
      const常量有具体的类型,在编译期会执行类型检查
  在使用中尽量以const替换宏定义,可以减小犯错误的概率

const关键字修饰指针

#include <iostream>

using std::cout;
using std::endl;

int main()
{
  int num1 = 10;
  int num2 = 20;

  //常量指针,pointer to const
  const int *p1 = &num1;
  cout << "*p1 = " << *p1 << endl;
  //常量指针,无法通过指针改变所指内容的值,但可以改变指针的指向
  p1 = &num2;
  cout << "*p1 = " << *p1 << endl;

  // 指针常量,const pointer
  int * const p2 = &num2;
  cout << "*p2 = " << *p2 << endl;
  //指针常量,无法改变指针的指向,但可以修改指针所指内容的值
  *p2 = 40;
  cout << "*p2 = " << *p2 << endl;

  return 0;
}

const关键字修饰成员函数

  把const关键字放在函数的参数表和函数体之间,称为const成员函数
const成员函数的格式
类型 函数名 (参数列表) const
{
  函数体
}
const成员函数的特点
  - 只能读取类数据成员,不能修改
  - 只能调用const成员函数,不能调用非const成员函数

const关键字修饰对象

  在创建类对象的时候,在类名前面添加关键字const,即可以创建const对象
const对象的特点
  - const对象只能被创建、撤销以及只读访问,不允许修改
  - 能作用于const对象的成员函数,除了构造函数和析构函数,就只有const成员函数
原文地址:https://www.cnblogs.com/xkyrl/p/14661697.html