2013-02-08 81 views
1

我在這裏不理解。在下面的代碼中,我定義了一個整數和一個常量整數。使用const int * const指針指向一個int

我可以有一個常量指針(int * const)指向一個整數。請參閱第四行代碼。

相同的常量指針(int * const)不能指向常量整數。見第五行。

一個指向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? 
+3

好像你對const關鍵字的含義有誤解。 'const int *'並不意味着「我指向的int是const」,這意味着「我不會使用這個指針來改變我指向的int。」無論你指向的int是否爲const,都不會改變發生的事情。 – Bill 2013-02-08 20:14:51

+0

感謝您的答覆和評論。就像比爾在評論中寫的那樣,我錯了。 C++有時很難得到。 – 2013-02-11 11:27:58

回答

1

您可以隨時決定不修改非常量變量。

const int* const constPointer4 = &variable; 

就解析定義:constPointer4是一個常量(即你不能改變它指向了)指向一個const int的(即variable)。這意味着即使您可以通過其他方式修改variable,也無法修改variableconstPointer4

反過來(通過非const指針訪問const變量),您需要一個const_cast

爲什麼指向const的指針有用?它允許您在類中有const成員函數,您可以向用戶保證該成員函數不會修改該對象。

1

const比non const有更少的訪問權限,這就是爲什麼它被允許。您將無法通過指針更改「變量」,但這並不違反任何規則。

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

在調用函數時,您會使用這個「const指針指向非常量變量」的情況。

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

f(&variable); 
1
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.

0

指向一個常量對象可以不是B e用於修改該對象。其他人是否可以修改它並不重要;它不能通過該指針完成。

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 
0

4號線

int* const constPointer2 = &constVar; 

這不應該被允許的,因爲「詮釋* const的constPointer2」的INT * const的一部分意味着該指針含量的不同,然後當你繼續和分配它& constVar

0

隨着繼續的問題asked-

1.int變量= 5;

2.const INT * constpointer =變量,使用指針//我們不能改變的變量

3.variable = 6的價值; //我們改變constpointer指向什麼矛盾的第二個聲明

理想情況下,除非第1條語句中的變量固定,否則不應允許使用第二條語句。不是嗎?如果我錯了,請糾正我。

相關問題