2010/03/21

[C++] const的意義(const pointer, pointer to const, const pointer to a const, const function...)

#include<iostream>

#include<string>

using namespace std;

class A

{

private:

    int y;

public:

A(){

y=0;

}

int f1(int x) const // 此const代表此function不可以修改Data Member

{

x++;

// y++; // Error! y為Data Member,因此不可以修改

return y;

}

const int f2(int x) // 回傳值為const

{

x++;

y++;

return y;

}

int f3(int const x) // 參數為const

{

// x++; // Error! x為const,不可以修改

y++;

return y;

}

void f4(int const *x) // x is variable pointer to a constant integer,也可以寫成f4(const int *x)

{

// (*x)++; // Error! pointer x所指向的實體為const,因此不可以修改其值

*x++; // 此行的意思是*(x++),先修改pointer x的值,在指向實體

}

void f5(int const &x) // x is variable reference to a constant integer

{

// x++; // Error! x就是一個const

}

void f6(int *const x) // x constant pointer to a variable integer

{

(*x)++;

// *x++; // Error! Constant pointer x 不可以指向其他實體

}

const char * f7() // 回傳一個variable pointer to a constant char

{

return "ABC";

}

void f8(const int * const x) // x is constant pointer to a const integer

{

// (*x)++; // Error! x所指向的實體為const,因此不可以修改其值

// *x++; // Error! Constant pointer x 不可以指向其他實體

}

};

int main(){

A a;

int x=3;

a.f1(x);

a.f2(x);

a.f3(x); // int x 會自動轉成const int x傳入

a.f4(&x) ;

a.f5(x) ;

const char *s = a.f7(); // 必須使用一個const來接const

// s[0]='0'; // Error! 無法對const 變數進行改變動作

return 0;

}

 

Reference: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

1 則留言:

Unknown 提到...

謝謝你!
這篇讓我釐清很多const的觀念!

2024年React state management趨勢

輕量化 在過去Redux 是 React 狀態管理的首選函式庫。 Redux 提供了強大的功能和靈活性,但也帶來了一定的學習成本和複雜度。 隨著 React 生態的不斷發展,越來越多的開發者開始追求輕量化的狀態管理函式庫。 Zustand 和 Recoil 等庫以其簡單易用、性...