const 与指针 *
int main()
{
int int_value = 1;
const int const_int_value = 2;
int const int_const_value = 3; // equal to ( const int )
const int const const_int_const_value = 4; // equal to ( const int )
const_int_value = 0; // ERROR // const_int_value is a constant value
//----------------------------------------------
int *int_pointer = &int_value;
const int *const_int_pointer = &int_value;
int const *int_const_pointer = &int_value; // equal to ( const int * )
int *const int_pointer_const = &int_value;
//*const_int_pointer = 0; // ERROR // 指针指向的地址存储的数据是常量
const_int_pointer = &const_int_value; // OK // 指针自身为变量
*int_pointer_const = 0; // OK // 指针指向的地址存储的数据是变量
//int_const_pointer = &int_value_temp; // ERROR // 指针自身为常量
//----------------------------------------------
const int *const const_int_pointer_const = &int_value;
int const *const int_const_pointer_const = &int_value; // equal to ( const int *const )
*const_int_pointer_const = 0; // ERROR //指针自身为常量且指针指向的地址存储的数据为常量
const_int_pointer_const = &int_value; // ERROR //指针自身为常量且指针指向的地址存储的数据为常量
//----------------------------------------------
system("pause");
return 0;
}
总结:
1、int * const 和 const int * 区分的方法:观察const直接修饰的元素(就近原则)
- int * const 即 const 直接修饰指针,则指针自身为常量;
- const int * 即 const 直接修饰 int ,则指针指向的地址存储数据为常量;
2、int const 和 const int const 两者与 const int 用法一致,内部均表示为 const int,推荐直接使用 const int ;
3、int const * const 与 const int * const 用法一致,内部均表示为 const int * const,推荐直接使用 const int * const;
const修饰类的成员函数
class MyClass
{
public:
void ConstFunction() const
{
std::cout << "my_int_value:" << '\n';
//my_int_value = 2; // ERROR // const成员函数中不能改变任何成员变量的值
}
int my_int_value = 1;
};
const 与引用 &
int main()
{
int int_value = 1;
const int const_int_value = 2;
int *int_pointer = &int_value;
const int *const_int_pointer = &int_value; //指针指向地址的数据为常量
int *const const_pointer_int = &int_value; //指针自身为常量
//----------------------------------------------
//int & int_refer = 0; // ERROR //非常量引用的初始值必须为左值
int & int_refer = int_value; // OK
//int & int_refer = const_int_value; // ERROR //将 "int &" 类型的引用绑定到 "const int" 类型的初始值设定项时,限定符被丢弃
int & const int_refer_const = int_value;// equal to ( int & )
//----------------------------------------------
const int & const_int_refer = 0;
const int & const_int_refer = int_value;
const int & const_int_refer = const_int_value;
int const & int_const_refer = int_value; // equal to ( const int &)
//int_const_refer = 0; // ERROR
//----------------------------------------------
int *& int_pointer_refer = int_pointer; // OK
//int *& int_pointer_refer = const_pointer_int; // ERROR 将 "int *&" 类型的引用绑定到 "int *const" 类型的初始值设定项时,限定符被丢弃
//----------------------------------------------
const int *& const_int_pointer_refer = const_int_pointer;
int *const & const_int_pointer_refer = const_pointer_int;
//----------------------------------------------
system("pause");
return 0;
}