据我所知,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 社区版)