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;
}
有错误的地方欢迎大家评论。
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;
}
有错误的地方欢迎大家评论。
相关文章推荐
- C++中static_cast、const_cast、reinterpret_cast的用法举例,附带举例说明强制类型转换时int和int&的区别
- const 用法说明
- 关于 const 用法说明
- C++中static_cast、const_cast、reinterpret_cast的用法举例,附带举例说明强制类型转换时int和int&的区别
- const的常见使用说明,用法
- CONST的用法
- 【c++】C++中const用法总结
- NSString的详细用法及其类方法的说明1
- scrollTop是什么及用法说明
- Mysql字符串截取函数SUBSTRING的用法说明
- C/C++中const用法小结
- const的用法详解
- 话说C语言const用法
- C++中const用法总结
- const用法(1) 定义常量
- Const用法小结
- 生命周期,作用域的定义;说明全局变量、静态变量、局部变量、const变量的生命周期、作用域
- c/c++中const用法总结
- 【转】const 用法总结(C++)
- pragma pack(非常有用的字节对齐用法说明)