• <td id="46i6g"><rt id="46i6g"></rt></td>
    <td id="46i6g"><kbd id="46i6g"></kbd></td>
  • <xmp id="46i6g"><option id="46i6g"></option><option id="46i6g"><option id="46i6g"></option></option>
  • <td id="46i6g"></td>
    發布時間:2020-09-28 23:17 原文鏈接: 再論C++中的const和引用(二)

    輸出結果:

    root@txp-virtual-machine:/home/txp# ./a.out
    y = 8
    p = 0x7ffd78559684

    代碼版本三:

    #include <stdio.h>
    int main()

        volatile const int y = 2;
        int *p = const_cast<int*>(&y);
        *p = 8;
         printf("y = %d",y);
         printf("p = %p",p);
         const int z = y ;//只讀變量
         p = const_cast<int*>(&z);
         *p= 9;
         printf("z = %d",z);
         printf("p = %p",p);
          return 0;

    輸出結果:

    root@txp-virtual-machine:/home/txp# ./a.out
    y = 8
    p = 0x7ffc5d651250
    z = 9
    p = 0x7ffc5d651254

    代碼版本四:

    #include <stdio.h>
    int main()

        char c = 'c';
        char& rc = c;
        const int& trc = c; // char 類型默認轉換為 int;const 引用初始化類型不同,將得到新的只讀變量,所以改變 rc 和 trc 沒有絲毫關系,從我們的輸出結果可以看出來
        rc = 'a';
        printf("c = %c",c);
        printf("rc = %c",rc);
        printf("trc = %c",trc);
        return 0;

    結果輸出:

    root@txp-virtual-machine:/home/txp# ./a.out
    c = a
    rc = a
    trc = c

    二、引用的總結:

    1、引用與指針有什么關系,以及如何理解"引用的本質就是指針常量"?

    (1)指針是一個常量:

    值為一個內存地址,不需要初始化,可以保存不同的地址

    通過指針可以訪問對應內存地址中的值

    指針可以被const修飾成為常量或者只讀變量

    (2)引用只是一個變量的新名字:

    對引用的操作(賦值、取地址等)都會傳遞到代表的變量上

    const引用使其代表的變量具有只讀屬性

    引用必須在定義時初始化,之后無法代表其它變量

    (3)從使用c++語言的角度來看:

    引用與指針沒有任何的關系

    引用是變量的新名字,操作引用就是操作對應的變量

    (4)從c++編譯器的角度來看:

    為了支持新概念"引用"必須要一個有效的解決方案

    在編譯器內部,使用指針常量來實現"引用"

    因此"引用"在定義時必須初始化


  • <td id="46i6g"><rt id="46i6g"></rt></td>
    <td id="46i6g"><kbd id="46i6g"></kbd></td>
  • <xmp id="46i6g"><option id="46i6g"></option><option id="46i6g"><option id="46i6g"></option></option>
  • <td id="46i6g"></td>
    亚洲日本va中文字幕久久道具