const使用大全

来源:互联网 发布:php 商城开发哪个好 编辑:程序博客网 时间:2024/04/28 17:13

先看以下两个文章:

http://www.vckbase.com/document/viewdoc/?id=689

http://www.vckbase.com/document/viewdoc/?id=412

 

补充:

  1. #include <stdlib.h>     //system()
  2. #include <iostream>     //cout<<
  3. #include <memory>       //auto_ptr<>
  4. using namespace std;
  5. class MyClass
  6. {
  7. public:
  8.     int x;
  9.     MyClass()
  10.     {
  11.         //void constructor
  12.     }
  13.     ~MyClass()
  14.     {
  15.         //destructor
  16.     }
  17.     int MyFunc( int/*const*/ y )    
  18.     {
  19.         *y = 20;    // 改变外部变量的值 int MyFunc(const int  *y ) or int MyFunc( int const *y ) 时报错
  20.         x = *y ;    // 改变类内部变量值 int MyFunc( int  *y ) const 时报错
  21.         y = &x ;    // 改变传来的指针参数值 int MyFunc( int  *y ) const or int MyFunc( int* const y )  时报错
  22.         return 0;
  23.     }
  24.     int MyFunc2( int /*const*/ &y )    
  25.     {
  26.         y = 20;     // 改变外部变量的值 int MyFunc2(const int  &y ) or int MyFunc2( int const &y ) 时报错
  27.         x = y ;     // 改变类内部变量值 int MyFunc2( int  &y ) const 时报错
  28.         return 0;
  29.     }
  30. };
  31. //-----------------------------------------
  32. void Fun()
  33. {
  34.     //-----------------------------------------
  35.     MyClass m;
  36.     int z = 10;
  37.     m.MyFunc(&z);
  38.     printf("call MyFunc:  z=%d, MyClass.x=%d/t/n",z,m.x);   
  39.     m.MyFunc2(z);
  40.     printf("call MyFunc2:  z=%d, MyClass.x=%d/t/n",z,m.x);    
  41.     return;
  42.     //--------------------------------------------
  43. }
  44. void main()
  45. {
  46.     Fun();
  47.     system("pause");
  48. }
  49. //-----------------------------------------