You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中dynamic_cast转子类后判断Customer指针为nullptr异常问题

问题分析与解决

1. findByName函数的致命问题

你的findByName里的lambda存在未定义行为:当v->getCustom()为nullptr时,lambda没有返回值。C++要求lambda必须在所有分支都返回值,否则会导致find_if逻辑混乱,甚至返回非法迭代器。

修复后的lambda需明确返回false:

auto cmp =[name](Vehicle* v){
    if(v->getCustom() != nullptr) {
        return name == v->getCustom()->getCustomerName();
    }
    return false; // 必须添加该返回值
};

另外,find_if找不到匹配元素时会返回vehicles_.end(),直接解引用这个迭代器会触发崩溃,必须先检查合法性:

auto it = find_if(vehicles_.begin(), vehicles_.end(), cmp);
if (it != vehicles_.end()) {
    return *it;
}
return nullptr; // 找不到时返回nullptr,调用方需处理该情况

2. dynamic_cast后未检查转换结果

你直接使用dynamic_cast<Car*>(veh)的结果,没有检查c是否为nullptr。如果veh不是Car类型对象,dynamic_cast会返回nullptr,此时调用c->getCustom()会直接崩溃。必须补充检查:

Vehicle* veh = findByName(name);
if (!veh) {
    // 处理找不到车辆的逻辑
    return;
}
Car* c = dynamic_cast<Car*>(veh);
if (!c) {
    // 处理转换失败的逻辑(比如veh不是Car类型)
    return;
}

3. cout输出nullptr的行为差异

当c->getCustom()返回nullptr时,cout的输出行为没有统一标准:部分编译器输出0或nullptr,部分则输出空内容,也就是你看到的仅显示Customer: 。不能通过输出结果判断是否为nullptr,必须用if (c->getCustom() == nullptr)做明确判断。

4. 其他编译级错误

  • Car类中color_声明为int,但构造函数参数是string color,类型不匹配,需修正为string color_;
  • Vehicle类的getID()、setCustom()、getCustom()函数未实现,需补充:
int Vehicle::getID() const {
    return id_;
}

void Vehicle::setCustom(Customer* custom) {
    custom_ = custom;
}

Customer* Vehicle::getCustom() const {
    return custom_;
}

内容的提问来源于stack exchange,提问作者Nexxizz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:01:00