您的位置:首页 > 编程语言 > C语言/C++

C++ 关键字理解

2015-09-24 09:52 309 查看
一、const 关键字

1、定义常量
const int PI = 3.1415;

2、修饰函数

void Function(int a) const
{
}
该关键字限定成员函数不可修改成员变量

3、修饰变量

void  Test1(int const*  p)
{
    *p = 12;   //error C3892: “p”: 不能给常量赋值
    p++;       //ok
}

void  Test2(int* const p)
{
    *p = 12;   //ok
    p++;       //error C3892: “p”: 不能给常量赋值
}


说明:const 在*的左侧,说明指针指向的内容不可修改,如test 1,如果const 在*右侧,说明指针变量不可修改(指针本身)

二、const 和mutable

volatile class B : public  A1,public A2
{
public:
mutable int a1;
int a2;
};
void main()
{
const B b;
b.a1 = 12;	//ok
b.a2 = 21;   // error C3892: “b”: 不能给常量赋值
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: