说明:const是属于左结合的类型修饰符,这里只讲怎么使用。
1、const 变量
//定义Const变量 常量
const int value1 = 1; // value1不可变
int const value2 = 2; // value2不可变</span>
2、const与指针
const int * p_str1 ; // *p_str1 不可变 p_str1是可以改变的
int * const p_str2 ; // p_str1 不可变 *p_str1是可以改变的
const int * const p_str3;// p_str1 不可变 *p_str1 不可变</span>
上述中:const 的指针可以接受 const指针和非const指针, 但非const的指针 只能接受非const的指针,所以 const指针的能力更强大些。
1)、const修饰函数的参数
void function_1(const int value); // value 的值不可改变
void function_2(const int * p_value); // (*p_value) 的值不可改变(注意括号)
void function_3( char * const p_str); // p_str的值不可改变(这里的p_str是指针变量)
2)、const修饰函数的返回值
const int function_4(); // 这里无意义
const int * function_5(); // const int * p = function_5();
int * const function_6() // int * const p = function_6();
以上C/ C++均可。
以下属于C++内容:
4、const与引用
这里怎么感觉都不太好讲清楚,又不想写太长,见下一篇中讲解到引用时在具体说明。
class A
{
public:
A(int x):value(x){};
int b()
{
//value++; // Error value不可改变
return value;
};
int c() const // 修饰成员函数
{
return value;
};
private:
const int value; // 修饰成员变量
};
const A a;
a.b(); // Error
a.c(); // OK
// 所以 const对象只能调用const成员函数