如何解决指针值失去作用范围
在方法callTest中,我声明了一个指向称为testPtr的int的指针。 然后,我将其传递给分配它的方法测试。由于指针不再是nullptr,因此我可以打印该值。但是,当我离开a :: test的范围时,我再次看到指针为null。我为之困惑。
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
时的行为没有什么不同。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。