指针值失去作用域
Pointer value loses scope
在方法 callTest 中,我声明了一个指向名为 testPtr 的 int 的指针。
然后我将它传递给分配它的方法测试。由于指针不再是 nullptr,我可以打印该值。但是,当我离开 a::test 的范围时,我看到指针再次为空。很纳闷是什么原因。
class a
{
public:
a();
protected:
void a::callTest()
void test(const int* intPtr) const;
private:
int mIntTest;
}
a::a() : mIntTest(7)
{
}
void a::callTest()
{
printf("a::callTest mIntTest = %d\n",mIntTest);
int* testPtr = nullptr;
// set the value of the pointer
test(testPtr);
if (testPtr == nullptr) {
printf("a::callTest testPtr STILL NULLPTR\n");
} else {
printf("a::callTest test ptr = %d\n",*testPtr);
}
}
void a::test(const int* intPtr) const
{
intPtr = &mIntTest;
if (intPtr != nullptr) {
printf("a::test intPtr = %d\n",*intPtr);
}
}
output:
s::callTest mIntTest = 7
a::test intPtr = 7
a::callTest intPtr STILL NULLPTR
您需要通过引用传递指针:
void a::test(const int* & intPtr) const
// ^ like this
否则您将通过副本传递它,调用者将看不到函数内部所做的更改。这与通过复制或通过引用传递 int
没有什么不同,行为是相同的。
在方法 callTest 中,我声明了一个指向名为 testPtr 的 int 的指针。 然后我将它传递给分配它的方法测试。由于指针不再是 nullptr,我可以打印该值。但是,当我离开 a::test 的范围时,我看到指针再次为空。很纳闷是什么原因。
class a
{
public:
a();
protected:
void a::callTest()
void test(const int* intPtr) const;
private:
int mIntTest;
}
a::a() : mIntTest(7)
{
}
void a::callTest()
{
printf("a::callTest mIntTest = %d\n",mIntTest);
int* testPtr = nullptr;
// set the value of the pointer
test(testPtr);
if (testPtr == nullptr) {
printf("a::callTest testPtr STILL NULLPTR\n");
} else {
printf("a::callTest test ptr = %d\n",*testPtr);
}
}
void a::test(const int* intPtr) const
{
intPtr = &mIntTest;
if (intPtr != nullptr) {
printf("a::test intPtr = %d\n",*intPtr);
}
}
output:
s::callTest mIntTest = 7
a::test intPtr = 7
a::callTest intPtr STILL NULLPTR
您需要通过引用传递指针:
void a::test(const int* & intPtr) const
// ^ like this
否则您将通过副本传递它,调用者将看不到函数内部所做的更改。这与通过复制或通过引用传递 int
没有什么不同,行为是相同的。