C++ 关键字 const
9. Const
- declares a variable to have a constant value
- Constants are variables
- Observe(遵守) scoping rules
- Declared with "const" type modifier
9.1 Compile time constants
- 编译时刻,可以确定值
- value must be initialized
- unless you make an explicit extern declaration;
const int bufsize = 1024;
// extern 声明
extern const int bufsize;
9.2 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
9.3 Pointers and const
char* const q = "abc"; // q is const
*q = 'c'; // OK
q++; // ERROR
const char *p = "ABCD"; // (*p) is a const char
*p = 'b'; // ERROR
Person p1("Fred", 200);
const Person* p = &p1;
Person const* p = &p1;
Person *const p = &p1;
// const 位于星号前面,对象是 const
// const 位于星号后面,指针是 const
9.4 示例
a.cpp
#include <iostream>
using namespace std;
int main()
{
//char *s = "hello world";
// "hello world": 位于代码段, 代码段的内容,不能写
char s[] = "hello world";
// "hello world": 位于栈中
cout << s << endl;
s[0] = 'B';
cout << s << endl;
return 0;
}
9.5 const 函数
- Repeat the const keyword in the definition as well as the declaration
- Function members that do not modify data should be declared const.
- const memeber functions are safe for const objects.
int Date::set_day(int d) {
day = d;
}
int Date::get_day() const {
day++; // ERROR modifies data member
set_day(12); // ERROR calls non-const member
return day; // ok
}
9.6 类中的 const
main.cpp
#include <iostream>
using namespace std;
class A {
int i;
public:
A() : i(0) {}
void f() { cout << "f()" << endl; }
void f() const { cout << "f() const" << endl; }
};
int main()
{
const A a;
a.f();
return 0;
}
// 解释:
// void f() 实际为: void f(A* this)
// void f() const 实际为: void f(const A* this)
- 运行结果
9.7 C 与 C++ const 区别
- C 语言版本
#include <stdio.h>
int main()
{
const int a = 10;
int* p = NULL;
p = &a;
*p = 20;
printf("a: %d\n", a);
system("pause");
return 0;
}
- C++ 版本
#include "iostream"
// C++ 中,const 是一个真正的常量
int main()
{
const int a = 10;
int* p = NULL;
p = (int *)&a;
*p = 20;
std::cout << "a 地址:" << &a << "\ta的值:" << a << std::endl;
std::cout << "p 地址: " << p << "\t*p的值:" << *p << std::endl;
system("pause");
return 0;
}
9.7.1 总结
C++ 编译器对 const 常量的处理:
- 当碰见常量声明时,会在符号表中放入常量;
- 编译过程中若发现使用常量,则直接以符号表中的值替换;
- 编译过程中若发现对 const 使用 extern 或者 &操作符,则给对应的常量分配存储空间(兼容C)
// TODO: 待插入图片
参考链接: