1. 常量变量
const 可用于声明常量变量。常量变量是在初始化后无法更改其值得变量。常量变量必须在声明时进行初始化
const int i = 10;
2. 指向常量的指针
指向常量的指针: 指针指向的内容不能被改变。
const int * u; // a pointer point to const int
int const * u; // a pointer to an int which is of const type
3. 常指针
常指针:指针的指向不能被改变。在可以更改值但不能移动内存的情况下很有用。
int x = 1;
int * const w = &x; // a pointer, which is const, that point to an int
4. 指向常量的常指针
指向常量的常指针:指针的指向和指向的内容均不能被改变。
int x = 12;
const int * const m = &x;
5. 函数的参数为常量
传入的参数在函数中不能被改变
void f(const int arg)
{
...
}
6. 函数的返回类型为常量
const int f()
{
return 1;
}
- 对于内置数据类型,返回 const 和非 const 值没有任何区别
- 对于用户定义的数据类型,返回 const 将阻止对其进行修改
- 程序执行时创建的临时对象始终为 const 类型
- 如果函数具有非 const 参数,则在调用时不能传入 const 参数
- 具有 const 类型参数的函数可以传递 const 类型参数和非 const 参数
7. 将类的数据成员定义为 const
它们在声明期间未初始化。它们的初始化在构造函数中完成。
class Test
{
const int i;
public:
Test(int x):i(x)
{
cout << "\ni value set: " << i;
}
};
int main()
{
Test t(10);
Test s(20);
}
8. 定义类对象为 const
当使用 const 关键字声明或创建对象时,在其生存期内,其数据成员将永远无法更改。
const Test t(30);
9. 定义类的成员函数为 const
const 成员函数不能修改对象中的数据成员
class StarWars
{
public:
int i;
StarWars(int x) // constructor
{
i = x;
}
int falcon() const // constant function
{
/* can do anything but will not modify any data members */
cout << "Falcon has left the Base";
}
int gamma()
{
i++;
}
};
int main()
{
StarWars objOne(10); // non const object
const StarWars objTwo(20); // const object
objOne.falcon(); // No error
objTwo.falcon(); // No error
cout << objOne.i << objTwo.i;
objOne.gamma(); // No error
objTwo.gamma(); // Compile time error
}
const 与 #define 的比较
#define
是预处理器指令,而const
是关键字#define
不是范围控制的,而const
是范围控制的- 通过包含相关的头文件,宏可以在程序或其他文件中的任何位置使用
#define
可以重新定义,但const
不能const
定义的变量有类型,而#define
没有