2010年8月15日 星期日

Array vs Point , Const vs Non-Const

#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
  {
    char const *p = "123456";   // Correct! value(rw), point to value(r)
    char       a[] = "123456";  // Correct! value(rw), location(r)
    // p[-]------> [1][2][3][4][5][6] (in read only section)
    //            a[1][2][3][4][5][6] (in read and write section)
    cout << typeid("123456").name() << endl;
    // char const [] same char const *
    int b = 0;
    int *pb = (int *)(&b);
  }
  {
    // non const auto -> const
    int i = 0, *ip = &i, **ipp = &ip, * **ippp = &ipp, * ***ipppp = &ippp;
    int         *       *       *       *       * ippppp     = &ipppp;

    int         *       *       *       * const *ippppcp    = ippppp;  // 可以
    int         *       *       * const *const *ipppcpcp   = ippppp;   // 可以
    int         *       * const *const *const *ippcpcpcp  = ippppp;    // 可以
    //int const *       * const *       * const * icppcppcp  = ippppp; // 不行
    //int       * const *       * const * const * ipcppcpcp  = ippppp; // 不行
    //int const * const *       * const *       * icpcppcpp  = ippppp; // 不行
  }
  {
    int                         i     = 0;
    int                        *ipc   = (int *)&i;
    int                *const *ipcp  = (int         * *)&ipc;
    //                    ^------------------------------^           自動補const
    int        *const *       * ipcpp = (int * const * *)&ipcp;

  }
  {
    int const i = 0;
    int                *ip   = (int         const *)&i;  // error
    //            ^---------------------------^           找不到const可以丟
    int const *       * icpp = (int       * *)&ip;       // error
    //            ^---------------------------^           不用轉const
    //    ^---------------------------^                   補const需要連續固無法補
  }
  system("pause");
  return EXIT_SUCCESS;
}

沒有留言:

張貼留言