1

ここで何かがわかりません。次のコードでは、整数と定数整数を定義しました。

整数を指す定数ポインター(int * const)を持つことができます。コードの4行目を参照してください。

同じ定数ポインター(int * const)は、定数整数を指すことはできません。5行目を参照してください。

const(const int * const)への定数ポインターは、定数整数を指すことができます。それが私が期待することです。

ただし、同じ(const int * const)ポインターは、非定数整数を指すことができます。最後の行を参照してください。なぜまたはどのようにこれが可能ですか?

int const constVar = 42;
int variable = 11;

int* const constPointer1 = &variable;
int* const constPointer2 = &constVar; // not allowed
const int* const constPointer3 = &constVar; // perfectly ok
const int* const constPointer4 = &variable; // also ok, but why?
4

5 に答える 5

2
int const constVar = 42;  // this defines a top-level constant
int variable = 11;

int *const constPointer1 = &variable;

int *const constPointer2 = &constVar; // not allowed because you can change constant using it

const int *const constPointer3 = &constVar; // perfectly ok. here you can't change constVar by any mean. it is a low level constant.

const int *const constPointer4 = &variable; // also ok, because it says you can't change the value using this pointer . but you can change value like variable=15 .

*constPointer4=5; //you get error assignment of readonly location.because that pointer is constant and pointing to read only memory location.

于 2013-02-08T19:22:27.637 に答える
1

constは、non constよりもアクセス権が少ないため、許可されています。ポインタを介して「変数」を変更することはできませんが、それはルールに違反していません。

variable = 4; //ok
*constPointer4 = 4; //not ok because its const

関数を呼び出すときは、この「非const変数へのconstポインター」状況をよく使用します。

void f(const int * const i)
{
    i=4; //not ok
}

f(&variable);
于 2013-02-08T19:19:04.980 に答える
1

非定数変数を変更しないことはいつでも決定できます。

const int* const constPointer4 = &variable;

定義を解析するだけです:constPointer4 const int(ie variable)へのconst(つまり、それが指しているものを変更することはできません)ポインタです。これは、他の方法で変更できる場合でも、をvariable 介して 変更できないことを意味します。constPointer4variable

逆に(非constポインターを介してconst変数にアクセスする)、が必要になりconst_castます。

constへのポインタが役立つのはなぜですか?これによりconst、そのメンバー関数がオブジェクトを変更しないことをユーザーに保証できるクラスにメンバー関数を含めることができます。

于 2013-02-08T19:19:24.807 に答える
0

constオブジェクトへのポインタを使用して、そのオブジェクトを変更することはできません。他の誰かがそれを変更できるかどうかは関係ありません。そのポインタを介して実行することはできません。

int i;               // modifiable
const int *cip = &i; // promises not to modify i
int *ip = &i;        // can be used to modify i

*cip = 3; // Error
*ip = 3;  // OK
于 2013-02-08T19:27:24.230 に答える
0

4行目

int* const constPointer2 = &constVar;

ここでは、「int *constconstPointer2」のint*const部分がポインターが一定であることを意味し、先に進んでそれを&constVarに割り当てるため、許可されるべきではありません。

于 2013-02-08T19:32:24.483 に答える