2016-04-08 109 views
1

我目前正在尝试学习一些C++,并遇到以下不直观的行为。由于t是指向const int的指针,我希望*t保持不变,只要我们不改变t即可。为什么常量整数指针指向一个非常量整数?

#include <iostream> 
using namespace std; 
int main(int argc, char *argv[]) 
{ 
    int a = 3; 
    const int* t = &a; //Why is this allowed? a is NOT const int 
    a = 4; 
    cout << *t << endl; //This does then print 4 
    //*t = 4; //Throws error. 

    return 0; 
} 

任何人都可以解释为什么这是编译?

+0

为了澄清我会建议没有指针的混乱。 'int a = 1; const int b = a;'就好了,现在'b'是const,而'a'不是,即使保持相同的值 – user463035818

+0

@ tobi303是的,但是在你的例子中'b'接收* copy * of 'a'的值。 – flawr

+1

那么,那么'int a = 1; const int&b = a;'now'b'是'b'的一个引用,但是即使'a'不是const也不能通过'b'改变这个值 – user463035818

回答

3

由于t是一个指向const int我希望*t将保持不变,只要我们不改变t

你不能做这样的假设在一般情况下,因为t可能指向非const对象,比如在你的榜样。

const int* t = &a; //Why is this allowed? a is NOT const int 

谁能解释这是为什么呢编译?

C++的规则允许将T*隐式转换为const T*。这是允许的,因为对非const对象有一个指向const(或引用)的指针是非常有用的。指向const的指针仅仅意味着对象不能被“通过”指针修改。对象本身可以是const,也可以是非const。

作为一个为什么它很有用的示例,您可以将某些可修改状态作为对象的私有成员,并返回const视图,以便其他人可以观察,但不能修改。这样一个实际的例子是std::string::c_str()。即使std::string的内部缓冲区是非常量,它也会返回const char*

+0

谢谢你的解释!现在通过*精确的变量来思考你可以做什么的类型时,它就很有意义。 – flawr

4

const int* t只是表示您不能更改指向t的值t,仅此而已。原来的价值可能会改变,但它与t的责任无关。

如果要保证价值不会改变,你应该让t指向一个常量,比如

const int a = 3; 
const int* t = &a; 

而对于这种情况下,你不能让一个int*指针指向它。

int* t = &a; // error 
+0

中移除。这很有道理。我预计'const int *'只能接受'const int'的地址! – flawr

+0

@flawr'int *'可以被隐式地转换为'const int *',这只是意味着你不会通过它改变它的值。例如,你可以传递一个'int *'函数,如果你不改变函数内部的值,你可以让函数把'const int *'作为参数。 – songyuanyao

-4

const int* t = &a; // int* or const int* can assgin to const int*

0

作为t是一个指向const int我希望*t将保持不变,只要我们不改变t

答案很简单:指针类型声明中的const关键字并不意味着“它是常量”,而是“您不允许修改它”。

这当您创建一个变量,然后调用另一个函数,用它做的东西,但你要禁止是有用的,例如修改:

extern int countZerosInArray(const int *array, int arrayLen); 

    int myVariableArray[ 100 ]; 
    // ... fill the array - i.e. modify it! 
    int noOfZeros = countZerosInArray(myVariableArray, 100); 

countZerosInArray功能被告知已只读访问到阵列,虽然阵列本身当然不是恒定的。

相关问题