What you are is God's gift to you.

What you make of yourself is your gift to God.

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

C++中的const的相关问题

这是我读了C++ Primier后的一个习作,供大家参考
#include
<iostream>

 

void main()

{

       //Version one, though we set a const double pointer to a non-const variable,

       //we still can't promise it won't be changed. Because the non-const variable can be

       //assigned to other pointer, and the latter pointer may be changed.

       double winWage1 = 6.1;

       std::cout << "Here is the common double number winWage1 : " << winWage1 << std::endl;

       const double* pDouble1 = &winWage1;

       std::cout << "Here is the const double number pointer pDouble1 ( point to winWage1 ) : " << *pDouble1 << std::endl;

 

       double* pDouble2 = &winWage1;

       *pDouble2 = 1.7;     //Changed

       std::cout << "Changed!!! pDouble1 has been changed by changing pDouble2, the value of pDouble1 now is :" << *pDouble1 << std::endl;

 

       //Version two. The better way to promise a value to be const is to declare itself as

       // a const value. And then, use const double pointer( your only choice ) to reference it.

       // Then the value won't be changed. But it's possible to change the const double pointer by

       // pass another const double reference to it, because this is valid.

       const double winWage2 = 6.1;

       std::cout << "Here is the const double winWage2 : " << winWage2 << std::endl;

       const double* pDouble3 = &winWage2;

       std::cout << "Here is the const double pointer pDouble3 ( point to winWage2 ) : " << *pDouble3 << std::endl;

 

       const double winWage3 = 1.5;

       std::cout << "Here is the const double winWage3 : " << winWage3 << std::endl;

       pDouble3 = &winWage3;

       std::cout << "The const double winWage2 is not changed, but the pointer pDouble3 that point to it has been changed ( point to winWage3 now ) : "

              << *pDouble3 << std::endl;

 

       //Version three. So if you want to promise that everything shouldn't be changed, you'd better

       // to use const double* const pointer

       const double* const pDouble4 = &winWage2;

       std::cout << "Here is the third version double point const double* const pDouble4 : " << *pDouble4 << std::endl;

 

 

}

/*Summary:

       OK. both can be changed.

       double a = 1;

       double* pa = &a;

 

       The variable can't be changed, but the pointer can.

       const double b = 2;

       const double* pb = &b;

       const double c = 3;

       pb = &c;  //pb has been changed.

 

       The pointer can't be changed.

       double d = 4;

       double* const pd = &d;

       d = 5;      //*pd has been changed, though the address of d, which is saved in pd is not changed.

 

       Both can't be changed.

       const double e = 6;

       const double* const pe = &e;

*/

posted on 2004-11-30 13:27  ykxie  阅读(236)  评论(0)    收藏  举报