如何定义一个类的常量呢?
在<高质量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.枚举类型定义的类的常量,类的内部使用,类的外部不能使用.