类的常量

来源:互联网 发布:开通58端口有什么用 编辑:程序博客网 时间:2024/05/20 10:23

如何定义一个类的常量呢?

在<高质量C++编程指南>中说不要考虑const.用枚举类型.

代码如下

  1. class A
  2. {
  3.  ...
  4.  enum { SIZE1=100,SIZE2=200 };//枚举常量
  5.  int array1[SIZE2];
  6.  int array2[SIZE2];
  7. };
  8.   

可我认为也可以用 const修饰符来实现,代码如下

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6.     
  7.  static const int SIZE1;
  8.  static const int SIZE2;
  9. };
  10. const int  A::SIZE1=100;
  11. const int A::SIZE2=200;
  12. int main()
  13. {
  14.    A::SIZE1=A::SIZE2;//出错,常量不可以赋值
  15.    cout<<A::SIZE1<<endl; 
  16.    return 0;
  17. }

也许有人会想,那他们之间是不是有区别呢?

是的,枚举类型和 static const两者是有区别的. 代码如下

 

  1. #include <iostream>
  2. using namespace std;
  3. class A
  4. {
  5. public:
  6.     
  7.  static const int SIZE1;
  8.  static const int SIZE2;
  9.  //int    Array[SIZE1];
  10.  //int    Array[SIZE2];
  11.  /*错误提示:
  12.  Compiling...
  13. file1.cpp
  14. F:/1/file1.cpp(10) : error C2057: expected constant expression
  15. F:/1/file1.cpp(10) : warning C4200: nonstandard extension used : zero-sized array in struct/union
  16. F:/1/file1.cpp(11) : error C2057: expected constant expression
  17. F:/1/file1.cpp(11) : error C2086: 'Array' : redefinition
  18. F:/1/file1.cpp(11) : error C2229: class 'A' has an illegal zero-sized array
  19. F:/1/file1.cpp(11) : warning C4200: nonstandard extension used : zero-sized array in struct/union
  20. Error executing cl.exe.
  21. */
  22. };
  23. const int A::SIZE1=100;
  24. const int A::SIZE2=200;
  25. int main()
  26. {
  27.   cout<<A::SIZE1<<endl; 
  28.   return 0;
  29. }

总结:

       1.static const 定义的类的常量,类的内部不能使用.

       2.枚举类型定义的类的常量,类的内部使用,类的外部不能使用.