const知多少
来源:互联网 发布:js 获取style display 编辑:程序博客网 时间:2024/05/03 13:02
看下面几种和指针有关的定义:
1)、const在前面
const int nValue; //nValue是const
const char *pContent; //*pContent是const, pContent可变
const (char *) pContent;//pContent是const,*pContent可变
char* const pContent; //pContent是const,*pContent可变
const char* const pContent; //pContent和*pContent都是const
2)、const在后面,与上面的声明对等
int const nValue; // nValue是const
char const * pContent;// *pContent是const, pContent可变
(char *) const pContent;//pContent是const,*pContent可变
char* const pContent;// pContent是const,*pContent可变
char const* const pContent;// pContent和*pContent都是const
记忆:(这个规则是错的)(因为“()”的出现,使得这个规则有时候是不成立的)沿着*号划一条线,如果const位于*的左侧,则const就是用来修饰指针所指向的变量,即指针指向为常量;如果const位于*的右侧,const就是修饰指针本身,即指针本身是常量。你可以根据这个规则来看上面声明的实际意义,相信定会一目了然。也可以根据const的左结合性质分析,如上面的pContent左边有*号,就与*号结合为一个整体,否则就单独出来,这样是不是更加容易记忆呢?
C++中,const指针可以接受const和非const地址,但是非const指针只能接受非const地址。const与define。两者都可以用来定义常量,但是const定义时,定义了常量的类型,所以更精确一些。
const关键字对类的操作:
思考为什么需要const成员函数?
我们定义的类的成员函数中,常常有一些成员函数不改变类的数据成员,也就是说,这些函数是"只读"函数,而有一些函数要修改类数据成员的值。如果把不改变数据成员的函数都加上const关键字进行标识,显然,可提高程序的可读性。其实,它还能提高程序的可靠性,已定义成const的成员函数,一旦企图修改数据成员的值,则编译器按错误处理。
非常量成员函数不能被常量成员对象调用,因为它可能企图修改常量的数据成员,但构造函数和析构函数对这个规则例外,它们从不定义为常量成员,但可被常量对象调用(被自动调用)。它们也能给常量的数据成员赋值,除非数据成员本身是常量。为了确保const对象的数据成员不会被改变,在C++中,const对象只能调用const成员函数。如果一个成员函数实际上没有对数据成员作任何形式的修改,但是它没有被const关键字限定的,也不能被常量对象调用。const成员函数的声明如下:
class X{
int i;
public:
int f() const;
};
关键字const必须用同样的方式重复出现在函数实现里,否则编译器会把它看成一个不同的函数:
int X::f() const{
return i;
}
- const知多少
- const你知多少?
- c++ const知多少
- C++ const知多少
- const知多少?
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly知多少
- const 与 readonly 知多少
- const全局常量占了多少空间
- 控制面板知多少
- XML知多少
- YONEX的羽毛球拍线
- Strlcpy和strlcat——一致的、安全的字符串拷贝和串接函数
- php open_basedir设置以及关于安全
- 如何控制Android不锁屏
- Json学习总结
- const知多少
- 修改 Cent OS yum源为中国镜像
- Android 助力云计算
- TCP网络拥塞控制
- 一起来学Objective-C(1)——Window下开发环境安装和Hello World
- Flex 错误大全
- google论文--mapred中文翻译
- MeeGo的DBus调试工具
- 数据模型(LP32 ILP32 LP64 LLP64 ILP64 )