伪代码,我不知道这是否编译,但你明白了.
class DataHolder
{
void GetData(float* ptr)
{
ptr = dataNeededByOtherClass;
}
float* dataNeededByOtherClass; // Initialized and modified elsewhere
};
class DataUser
{
void DoStuff()
{
float* ptrToData;
dataHolder->GetData(ptrToData);
// ptrToData points to garbage Why?
ptrToData = dataHolder->dataNeededByOtherClass;
// ptrToData now points to the correct data
}
};
Run Code Online (Sandbox Code Playgroud)
我在这看什么?
功能
void GetData(float* ptr)
Run Code Online (Sandbox Code Playgroud)
按值接收指针参数.ptr在函数内修改不会更改值ptrToData.相反,尝试通过指针传递指针:
void GetData(float** ptrptr)
{
*ptrptr = dataNeededByOtherClass;
}
float* ptrToData;
dataHolder->GetData(&ptr);
Run Code Online (Sandbox Code Playgroud)
PS请注意,以这种方式公开类变量不被视为最佳实践.
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |