类的常量
来源:互联网 发布:开通58端口有什么用 编辑:程序博客网 时间:2024/05/20 10:23
如何定义一个类的常量呢?
在<高质量C++编程指南>中说不要考虑const.用枚举类型.
代码如下
- class A
- {
- ...
- enum { SIZE1=100,SIZE2=200 };//枚举常量
- int array1[SIZE2];
- int array2[SIZE2];
- };
可我认为也可以用 const修饰符来实现,代码如下
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- static const int SIZE1;
- static const int SIZE2;
- };
- const int A::SIZE1=100;
- const int A::SIZE2=200;
- int main()
- {
- A::SIZE1=A::SIZE2;//出错,常量不可以赋值
- cout<<A::SIZE1<<endl;
- return 0;
- }
也许有人会想,那他们之间是不是有区别呢?
是的,枚举类型和 static const两者是有区别的. 代码如下
- #include <iostream>
- using namespace std;
- class A
- {
- public:
- static const int SIZE1;
- static const int SIZE2;
- //int Array[SIZE1];
- //int Array[SIZE2];
- /*错误提示:
- Compiling...
- file1.cpp
- F:/1/file1.cpp(10) : error C2057: expected constant expression
- F:/1/file1.cpp(10) : warning C4200: nonstandard extension used : zero-sized array in struct/union
- F:/1/file1.cpp(11) : error C2057: expected constant expression
- F:/1/file1.cpp(11) : error C2086: 'Array' : redefinition
- F:/1/file1.cpp(11) : error C2229: class 'A' has an illegal zero-sized array
- F:/1/file1.cpp(11) : warning C4200: nonstandard extension used : zero-sized array in struct/union
- Error executing cl.exe.
- */
- };
- const int A::SIZE1=100;
- const int A::SIZE2=200;
- int main()
- {
- cout<<A::SIZE1<<endl;
- return 0;
- }
总结:
1.static const 定义的类的常量,类的内部不能使用.
2.枚举类型定义的类的常量,类的内部使用,类的外部不能使用.
- 类的常量
- 类的常量
- 类常量的特点
- 类常量的访问
- 类的静态常量初始化
- ActionSupport类里的常量
- 类的静态常量成员
- 枚举类的常量定义
- File类的静态常量
- string 类返回常量字符串常量的对与错
- C++类的常量对象与常量成员函数
- 接口(类)常量与枚举常量的区别
- 指向常量的指针常量
- 常量指针、指针常量、指向常量的常量指针
- 指针常量,常量指针。指向常量的常量指针
- 指针常量,常量指针, 指向常量的常量指针
- 指针常量,常量指针。指向常量的常量指针 收藏
- 常量指针、指针常量以及指向常量的指针常量
- c# 中使用构构函数与IDisposable接口双重释放资源
- nameQuery异常解决方案(转自网络)
- GRUB入门和技巧:通过Windows XP安装GRUB到MBR区,并且使用中文菜单!
- 双系统重装(XP+Linux)小结
- hibernate绑定参数类型[ZT](转自网络)
- 类的常量
- [转]新员工上班前后分别与老板的对话
- 用时间做数据编号
- 完美企业网站的101项指标
- JavaMail使用完全手册
- 本Blog的申明
- JavaMail API简介
- VS2008快捷键大全
- Malcolm的新书:Outliers