关键字解释
const 常量定义关键字
const的全称是constant,不变的,在一个有效的作用范围内约束变量、指针、方法、对象;
const不能和static关键字一起使用,因为static没有一个有效的作用范围。
volatile 解指针关键字
如果是被const修饰的变量,如果想通过指针对变量再次进行修改,需要使用volatile,多变的;
mutable 解对象、方法变量关键字
const修饰的方法,里面的变量不能修改,使用mutable修饰的变量可以修改;
实例代码
class Readonly
{
public:
void Readout() const
{
// 类的方法是const,只读的方法,编译无法通过
// const在方法的后面说明方法不能修改类里面的数据
name = "Readonly";
}
private:
string name;
};
// const作为函数参数,数据在方法里面无法被修改
void Func1(const int v)
{
//v++; !Err
}
// const作为函数指针的类型,有3种
void Func2(const int* const v) // 指针和数据都不能被修改
{
int x = 1;
// *v = 1; !Err
// v = &x; !Err
}
void Func3(int* const v) // 右定值,指针不能被修改
{
int x = 1;
*v = 3;
// v = &x; !Err
}
void Func4(const int* v) // 左定值,数据不能被修改
{
int x = 3;
v = &x;
// *v = 1; !Err
}
// ---------- const 对于临时变量优化 -----------
class ConstExample
{
public:
ConstExample(int in) : mIndex(in){ }
// 外部的const的对象必须调用已经const约束的成员
int Get() const{ return mIndex; }
// const 不能和static一起使用,static不带*this,const必须明确在一个区域的范围
//static int SGet() const { return mSIndex; }
private:
int mIndex;
static int mSIndex;
};
// 临时的调用不需要重新构造一个对象,使用const约束对象不能改变
void Outter(const ConstExample & e)
{
cout << e.Get() << endl;
}
// ---------- const 对于变量特殊处理 -----------
// 实例:成员函数修改成员变量
class VarExample
{
public:
VarExample(int ix, int iy) : x(ix), y(iy){ }
void Change() const
{
//++x; Err const约束的方法不能修改内部的数据
// 但使用mutable修饰的可以解除const的方法约束
++y;
}
private:
int x;
mutable int y;
};
int main(int argc, char* argv[])
{
// const = constant常量,不变化的
// const修饰的变量,此变量为一个常量
const int x = 3;
// volatile的变量可以被修改,意为“易变的,多变的”
volatile const int y = 4;
// x = 4; &x; 编译出错
// y = 5; &y; 编译出错
int* p1 = (int*) &x; // x已经被const声明,无法被修改数据
*p1 = 5;
cout << "x:" << x << endl;
int* p2 = (int*) &y; // y已经被volatile const声明,可以被修改数据
*p2 = 5;
cout << "y:" << y << endl;
cout << "--------------" << endl;
int x1 = 7, y1 = 8;
// const修饰的指针有3钟情况,左定值,右定值,左右定值
const int* p3 = &x1;
// *p3 = 1; // 无法编译,const左定值保护数据不能被修改
int* const p4 = &y1;
*p4 = 1;
cout << "p4:" << *p4 << endl;
//p4 = &x1; // 无法编译,const右定值保护指针不能被修改
const int* const p5 = &x1;
//*p5 = 1; // 左右定值,数据和指针全部不能被修改
//p5 = &y1;
cout << "---------------" << endl;
ConstExample ce = { 3 };
Outter(ce);
}
C/C++的常量定义
有两种const的定义,假常量和真常量;
假常量可以被修改,真常量无法被修改。
代码实例
int main(int argc, char* argv[])
{
// const 是假常量,在有volatile解常量的情况可以被修改
// constexpr 是真常量,无论如何都不能修改
volatile const int x = 3;
volatile constexpr int x1 = 3;
int* p1 = const_cast<int*>(&x);
*p1 = 1; // 可以使用volatile来解常量,可以修改
int* p2 = const_cast<int*>(&x1);
*p2 = 1; // volatile也不能解,无法修改
cout << "x:" << x << endl;
cout << "x1:" << x1 << endl;
}