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)
- 运行结果
参考链接: