0

据我所知,const int *暗示我可以更改指针但不能更改数据,int * const说我不能更改指针地址但我可以更改数据,并const int * const声明我不能更改其中任何一个。

但是,我无法更改使用 type 定义的指针的地址const int *。这是我的示例代码:

void Func(const int * pInt)
{
    static int Int = 0;
    pInt = ∬
    Int++;
}

int wmain(int argc, wchar_t *argv[])
{
    int Dummy = 0;
    const int * pInt = &Dummy;
    //const int * pInt = nullptr;   // Gives error when I try to pass it to Func().
    std::cout << pInt << '\t' << *pInt << std::endl;
    std::cout << "-------------------" << std::endl;
    for (int i=0; i<5; i++)
    {
        Func(pInt);     // Set the pointer to the internal variable. (But, it doesn't set it!)
        std::cout << pInt << '\t' << *pInt << std::endl;
    }
     return 0;
}

代码输出:

00D2F9C4        0
-------------------
00D2F9C4        0
00D2F9C4        0
00D2F9C4        0
00D2F9C4        0
00D2F9C4        0

我希望在调用至少一次之后,地址pInt会更改为指向函数内部的内部变量。但事实并非如此。我一直指向变量。Func()Func()Dummy

这里发生了什么?为什么我没有得到我期望的结果?

(IDE:Visual Studio 2015 社区版)

4

1 回答 1

5

您在调用站点看不到更改,因为您正在按值传递指针。在里面修改它Func只会改变本地副本,而不是传入的指针。

如果要修改指针并使更改在外部可见,请通过引用传递它:

void Func(const int *& pInt)
//                   ^
于 2016-01-27T10:02:08.237 回答