我有一个定义如下的测试:
ClassName FileHandle;
ClassName1* data; //I want function to define this later
FileHandle.getData(data); //this is null after the call but isn't in function it calls
//why isn't the pointer defined from the method called? How fix?
它调用的函数如下所示:
void ClassName::getData(ClassName1* data)
{
char * buf = "lots of data";
data = new ClassName1(buf, sizeof(buf)); //it's in there
}
我确信这是我对指针和引用的理解的问题。你知道我在这里做错了什么吗?为什么当数据返回到我的测试时,数据的值仍未定义?
最佳答案
通过引用传递指针本身&
:
void ClassName::getData(ClassName1* &data2)
为了清楚起见,我将变量重命名为 data1
和 data2
,以便您可以看到它们是不同的。只有当通过引用传递时,它们实际上是相同的,否则在 getData
函数退出后,存储在本地指针 data2
中的地址将被销毁,并且原始存储在输入中的 NULL 地址data1
保持不变。
调用语法保持不变:
FileHandle.getData(data1);
关于c++ - 返回空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26896105/