close

目錄

目的

由簡入繁介紹使用方法

本文

With Plain Old Data

int const ic;               // const  variable
const int ci;               // == ic

With pointer/reference

int const * ic_p;           // const  variable, normal pointer
const int * ci_p;           // == ic_p

int *const i_pc;            // normal variable, const pointer
int const *const ic_pc;     // const  variable, const pointer
const int *const ci_pc;     // == ic_pc

int &const i_rc;            // Error,&const is not a declartor operator [1]
                            // reference is already h== const mean.

int const & ic_r;           // const  variable, reference
const int & ci_r;           // == ic_r

With function/member function

class test{
public:
    void foo() const{
        // if instance of Class:test is defined const, then call this function

        pri_i=10;           // Error, this function cannot change inner variable
        pub_i=10;           // Error, == pri_i, visibility of instance's variable is not influent for const
        sta_i=10;           // Pass, static variable belongs Class
    }
    void foo() {
        // if instance of Class:test
        // is non-const or not exactly append const
        // of same funciton
        // then this function will called

        // do something...
    }
    
    int pub_i;
private:
    int pri_i;
    static int sta_i;
};

With alias (typedef/using)

typedef int * t_ip;
t_ip const t_ipc;           // normal variable and const  pointer
const tip ct_ip;            // == t_ipc

using u_ip = int *;
u_ip const u_ipc;           // == t_ipc
const u_ip cu_ip;           // == t_ipc

// 如果你想要定義一個const variable,那必須於宣告別名時定義之:

typedef int const * t_icp;  // const  int and normal pointer
typedef const int * t_cip;  // == t_icp
t_icp const t_icpc;         // const  int and const  pointer
const ticp ct_icp;          // == t_icpc

// using and typedef are the same

參考資料

  1. TCPL *, &和*const皆是declarator operator
arrow
arrow

    Ernest 發表在 痞客邦 留言(0) 人氣()