您的位置:首页 > 其它

const的用法说明

2006-05-09 11:41 225 查看
const的几种用法:

1.const用来限制变量
const int a; //a的值为不可变
const int *p; //*p的值为不可变
int* const p; //p值为不可变
const int* const p; //p的值不可变,*p也不可变
2.cosnt用来限定函数
const int fun(void) //函数的返回值为不可变
int fun(void) const //函数不可以改变对象的状态。
//编译器将不允许此方法的任何数据成员执行赋值,自增,或自减操作
//也不允许此方法调用这一类的任何非常量方法
//对于常量对象只能调用声明为const的方法

说明: 可以使用const_case来解除const属性

上述用法用下列的例子来说明:

#include <iostream>
using namespace std;

class test
{
public:
test(void) { cout<<"Test"<<endl; }
~test(void) { cout<<"~Test"<<endl; }

void fun(void) { cout<<"Fun"<<endl; }
void fun1(void) const
{
//a = 3;//error
//fun();//error
fun2();//ok
cout<<"Fun1"<<endl;
}
void fun2(void) const
{
cout<<"Fun2"<<endl;
}
const int fun3(void)
{
return 5;
}
int a;
};

int _tmain(int argc, _TCHAR* argv[])
{
const int a = 3;
//a = 4;//error

int b = 4;

const int *cp = &b;
cp = &a;//ok
//*cp = 65; //error

int* const pc = &b;
//pc = &a;//error
*pc = 65;//ok

const int* const cpc = &b;
//cpc = &a; //error
//*cpc = 65; //error

const test oTest;
//oTest.fun();//error
oTest.fun1();//ok
oTest.fun2();//ok

test oTest1;
//int c = oTest.fun3();//error
const int c = oTest1.fun3();

return 0;
}

有错误的地方欢迎大家评论。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: