为什么函数可以改变`const char *& value`?

时间:2015-07-09 17:49:49

标签: c++ pointers reference const

这是以const char * &作为参数的函数示例。

#include <iostream>
using namespace std;

char test[] = "Test";

void func(const char * & str)
{
    str = &test[0];
}

int main() {
    const char * mytest;

    func(mytest);

    cout << mytest << endl;

    return 0;
}

为什么这样做? (http://ideone.com/7NwmYd

const在这里意味着什么?为什么func()可以更改str给定此功能?

UPD。这是一个新手问题,请不要减去它。

1 个答案:

答案 0 :(得分:3)

cost是指紧靠其左侧的声明部分,除非const是第一个特殊情况,在这种情况下紧接在右边:

const char * &  // the char is const, the * is not
char const * &  // the char is const, the * is not
char * const &  // the * is const, the char is not
char const * const &  // the char and * are both const

你有一个指向const char的非const指针并修改了指针(而不是char),所以编译器没有任何东西可以抱怨。