const
是类型修饰符, 通常用于修饰不可变变量 .
- 用于定义常量. 如:
const int num = 100;
定义常量一般也会使用#define
进行定义, 但使用const
的好处是, 编译器会进行类型检查, 而使用#define
则不会. - 使用const修饰的默认为
文件局部变量
, 即如果需要跨文件访问变量, 需要使用extern
进行初始化修饰, 如:extern int num = 100;
才能从另外一个文件进行访问. 而没有使用const
修饰的变量默认是extern
的, 不需要显式的使用extern
修饰. const
常量必须初始化. 如:
#include <iostream>
class num {
public:
const int a = 100;
public:
void print() const;
};
void num::print() const {
std::cout << "a: " << this->a << std::endl;
}
int main(void) {
auto n = num{};
std::cout << n.a << std::endl;
n.print();
}
const
与指针:
const char *str = "hello";
char *const str = "hello";
当 const
在 *
左边时, 不能通过 *str = "world;"
进行赋值, 即 *str
是不可变的. 当 const
在 *
右边时, 不能通过 str = nullptr;
进行赋值, 即 str
是不可变得.
- 可以将非
const
的指针赋值给const
的指针; 反之不行.
int num = 10;
const int *const_num = #
- 在函数参数中使用
const
, 可限制函数对参数的使用.
void copy(char *dst, const char *src);
通过对src
参数使用const
修饰, 要求copy
函数实现是不能通过src
变量修改源字符串的内容, 否则编译器会报错.
- 在类中初始化
const
成员.
#include <iostream>
class num {
public:
const int a;
public:
void print() const;
num(int a);
};
num::num(int a): a(a) { }
void num::print() const {
std::cout << "a: " << this->a << std::endl;
}
int main(void) {
auto n = num{100};
std::cout << n.a << std::endl;
n.print();
}
- 使用
static
修饰const
变量时, 可以在类内/外部进行初始化.
class num {
public:
static const int b;
static const int c = 100;
};
const int num::b = 100;
上面是对 const
用法的一点总结, 发现有新的用法会持续补充. 如果觉得有帮助,可以扫描右边的微信打赏码支持一下.