我在使用以下代码时遇到问题。我尝试在一个函数中填充名为 station
的对象的成员,但我无法在 main()
中检索它。
这是我的标题foo.h
class DirectoryProperties
{
public:
size_t numberOfFolders;
void initialize_stations( StationBase *station );
private:
void fill_station_names( StationBase *station );
};
class StationInfo
{
public:
std::string name;
};
这是我的foo.cpp
#include "foo.h"
void DirectoryProperties::fill_station_names( StationBase *station )
{
station[0].name = "dummy";
}
void DirectoryProperties::initialize_stations( StationBase *station )
{
size_t N = 1;
station = new StationBase[ N ];
this->fill_station_names( station );
// this works
std::cout << station[0].stationName << std::endl;
}
int main()
{
DirectoryProperties dirInfo;
StationBase *station = NULL;
dirInfo.initialize_stations( station );
// breaks here
std::cout << station[0].stationName << std::endl;
return 0;
}
因此,我可以在 DirectoryProperties::initialize_stations( StationBase *station )
中正确打印 station[0].name
,但在 main()
.
如果我尝试它也会中断
int main()
{
DirectoryProperties dirInfo;
StationBase *station = NULL;
dirInfo.initialize_stations( station );
// breaks here
station[0].stationName = "dummy";
return 0;
}
所以我假设对象指针 station
没有在 main
中分配内存。
最佳答案
station
是 initialize_stations
中的局部变量,所以对它的任何更改都不会在函数之外产生影响。
一个直接的解决方法是让函数返回一个指向新数组的指针。
StationBase* DirectoryProperties::initialize_stations( )
{
....
StationBase* station = new StationBase[ N ];
....
return station;
}
更好的解决方案是返回 std::vector<StationBase>
.或者只是一个 StationBase
,因为无论如何您只分配一个对象。
std::vector<stationBase> DirectoryProperties::initialize_stations()
{
size_t N = 1;
std::vector<stationBase> station(N);
fill_station_names( station );
return station;
}
并修复fill_station_names
相应地。
关于c++ - 检索函数内用 operator new 分配的类指针对象成员的值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221039/