What you are is God's gift to you.

What you make of yourself is your gift to God.

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

C++的引用相关

关于引用,与指针的区别在于引用一旦赋值,就与所引用的对象永久绑定,之后改变的就是所引用的对象,而绑定关系不会再改变。较多用于函数的传参。可视为对象的别名。
#include
<iostream>

 

void main()

{

       int iValue1 = 1;

       int &intRef1 = iValue1;

      

       std::cout << "Here is the original int value (iValue1) : " << iValue1 << std::endl;

       std::cout << "Here is the reference value of int (&intRef1) : " << intRef1 << std::endl;

      

       iValue1 = 2;

      

       std::cout << "Now the value of iValue1 has been changed to : " << iValue1 << std::endl;

       std::cout << "Now the value of (&intRef1) is : " << intRef1 << std::endl;

      

       int *intPointer1 = &iValue1;

       int *&intRef2 = intPointer1;

      

       std::cout << "Now there is a pointer intPointer piont \

              to the iValue1 and a reference intRef2 : " << *intRef2 << std::endl;

      

       int iValue2 = 12;

       intPointer1 = &iValue2;

      

       std::cout << "The pointer intPointer has been changed to iValue2 : " << *intPointer1 << std::endl;

       std::cout << "The value of intRef2 now is : " << *intRef2 << std::endl;

      

       const int &intRef3 = iValue1;                                                                                                                                                                                                                                       

      

       iValue1 = 3;

 

       const int iValue3 = 22;

       const int* const &intRef4 = &iValue3;

 

       const int* const int &intRef5 = &iValue3; //This is my idea. correct but will obtain a warning.

       const int* const &intRef6 = &iValue3;            //Better way, no warning.

 

       std::cout << "My idea : " << *intRef5 << std::endl;

       std::cout << "Better way : " << *intRef6 << std::endl;

}

posted on 2004-11-30 18:31  ykxie  阅读(235)  评论(0)    收藏  举报