【发布时间】:2021-07-14 15:15:01
【问题描述】:
我是 CPP 的新手,我正在编写一个程序来模拟火车路径系统,该系统包括目的地并开始使用面向对象编程。 我有 2 个班级,如下所示(有一个乘客班级,但不相关):
class Train
{
public:
int cooldown_time;
int travel_time;
int time_since_movement;
int id;
class Station *start;
class Station *destination;
vector<Passenger *> current_passengers;
string status;
void add_train(vector<string> commands, vector<Station> stations, vector<Train> &trains)
{
travel_time = stoi(commands[THIRD_PART + 1]);
cooldown_time = stoi(commands[THIRD_PART + 2]);
status = TSTATUS1;
start = station_search(stations, commands[SECOND_PART]); // this is where the problem happens
destination = station_search(stations, commands[THIRD_PART]);
id = stations.size();
}
};
class Station
{
public:
int tuffy_price;
string city_name;
vector<Passenger *> current_passengers;
vector<Train *> current_trains;
int id;
void add_station(vector<Station> &stations, vector<string> &commands)
{
tuffy_price = stoi(commands[THIRD_PART]);
city_name = commands[SECOND_PART];
id = stations.size();
}
};
我有一个搜索功能,专门用于根据用户输入的命令查找起点和目的地,例如:用户输入“add_train cityname1 cityname2
Station *station_search(vector<Station> stations, string key)
{
Station *dummy;
for (int i = 0; i < stations.size(); i++)
{
if (stations[i].city_name == key)
{
return &stations[i];
}
}
return dummy;
}}
我的问题是我的搜索函数的奇怪行为,当我调试程序时,我看到该函数找到正确的站对象并返回一个指向它的指针,但是当执行返回到构造函数时它是随机的(可能不是随机的)将与起始站相关的第一个指针变为空,并将其中的值替换为垃圾值。 但是函数搜索到目的站后并没有这样做,执行是正确的。
有人可以解释为什么会发生此错误吗? 我的猜测是我对局部变量和指针返回的理解不够好,并且我在某个地方犯了一个菜鸟错误,但我似乎没有找到它。
PS:我没有包含完整的代码,因为它太长了我可以通过附加文件来包含它,如果需要的话可以评论。
【问题讨论】:
-
OT:您应该删除
dummy,因为它从未初始化并返回nullptr,以便您可以看到何时找不到电台。 -
std::find_if可能会有所帮助 -
@SimonKraemer 感谢您的提示,我来自 C 背景,我不知道 nullptr 的语法,否则我可能已经忘记了。