我所知,const int *
意味着我可以更改指针但不能更改数据,int * const
说我不能更改指针地址,但我可以更改数据,const int * const
声明我不能更改其中任何一个。
但是,我无法更改用 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
我希望在调用Func()
至少一次后,pInt
的地址会更改为指向 Func()
函数内部的内部变量。但事实并非如此。我一直指向Dummy
变量。
这是怎么回事?为什么我没有得到我期望的结果?
(IDE:Visual Studio 2015 Community Version)
您不会在调用站点看到更改,因为您正在按值传递指针。在Func
内部修改它只会更改本地副本,而不是传入的指针。
如果要修改指针并使更改在外部可见,请通过引用传递它:
void Func(const int *& pInt)
// ^