2013-02-08 109 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条语句中的变量固定,否则不应允许使用第二条语句。不是吗?如果我错了,请纠正我。

相关问题