問題描述
運(yùn)行下面的代碼顯示&x=ptr,那么x和*ptr怎么不相等?
running the following code shows that &x=ptr, so how come x and *ptr are not equal?
const int x=10;
int* ptr =(int*) &x;
*ptr = (*ptr)+1;
cout << &x << " " << x << " " << ptr <<" " <<*ptr; //output : 0012FF60 10 0012FF60 11
推薦答案
C++ 實(shí)現(xiàn)只需要您遵守規(guī)則才能使程序運(yùn)行.你違反了規(guī)則.C++ 實(shí)現(xiàn)可能是這樣的:
The C++ implementation is only required to make a program work if you obey the rules. You violated the rules. The C++ implementation likely behaved this way:
- 因?yàn)?
x
被聲明為const
,C++ 實(shí)現(xiàn)知道只要你遵守規(guī)則,它的值就不會(huì)改變.因此,無論在何處使用x
,C++ 實(shí)現(xiàn)都會(huì)使用 10,而無需費(fèi)心檢查x
是否已更改. - 因?yàn)?
*ptr
指向一個(gè)非常量int
,所以實(shí)際執(zhí)行了存儲(chǔ)和讀取操作.這些工作"是因?yàn)樗赶虻膬?nèi)存(表示x
的地方)實(shí)際上并未被操作系統(tǒng)標(biāo)記為只讀.因此,您可以進(jìn)行修改,盡管您不應(yīng)該這樣做.
- Because
x
is declaredconst
, the C++ implementation knows its value cannot change as long as you obey the rules. So, whereverx
is used, the C++ implementation uses 10 without bothering to check whetherx
has changed. - Because
*ptr
points to a non-constint
, stores to it and reads from it are actually performed. These "work" because the memory it points to (wherex
is represented) is not actually marked read-only by the operating system. Thus, you are able to make modifications in spite of the fact that you are not supposed to.
請注意,如果您遵守規(guī)則,C++ 實(shí)現(xiàn)的行為將可以工作.如果您沒有修改 x
,那么在 x
出現(xiàn)的任何地方使用 10 都會(huì)正常工作.或者,如果您沒有將 x
聲明為 const
,那么 C++ 實(shí)現(xiàn)不會(huì)假定它總是 10,因此每當(dāng) x
被訪問.這就是 C++ 標(biāo)準(zhǔn)對實(shí)現(xiàn)的所有要求:如果你遵守規(guī)則,它就可以工作.
Observe that the behavior of the C++ implementation would work if you obeyed the rules. If you had not modified x
, then using 10 for x
wherever it appeared would have worked normally. Or, if you had not declared x
to be const
, then the C++ implementation would not have assumed it would always be 10, so it would get the changed value whenever x
was accessed. This is all the C++ standard requires of an implementation: That it work if you follow the rules.
當(dāng)您不遵守規(guī)則時(shí),C++ 實(shí)現(xiàn)可能會(huì)以看似不一致的方式中斷.
When you do not follow the rules, a C++ implementation may break in seemingly inconsistent ways.
這篇關(guān)于修改 C++ 中的 const int的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!