You need to enable JavaScript to run this app. C++责任链模式实现折扣功能时最终返回未打折原价问题排查
优惠活动
大模型
产品
解决方案
定价
更多

C++责任链模式实现折扣功能时最终返回未打折原价问题排查

问题根因

你的代码核心问题是责任链下游节点的计算结果没有被上游节点接收返回,实际执行流程如下:

  1. 主函数调用fixated1->countDiscount(basket),在该函数内计算得到总价120,120<150不满足当前折扣条件,进入else if (next != NULL)分支,调用fixated2->countDiscount(basket)
  2. fixated2的函数内计算总价120,满足满100减15的条件,计算得到105、打印日志后返回105
  3. 但返回到fixated1的调用位置后,你没有接收这个105的返回值,代码继续执行到fixated1的return totalPrice语句,返回的是fixated1中最初计算的未打折总价120,这就是你拿到错误结果的原因。
修复方案

修改FixatedDiscount.cpp中的countDiscount函数,在调用下一个折扣节点时,直接返回下游节点的计算结果即可:

#include "FixatedDiscount.h"
#include <iostream>

int FixatedDiscount::countDiscount(Basket b) {
    int totalPrice = b.countPrice();
    if (totalPrice >= limit) {
        totalPrice -= discount;
        std::cout << "Handled when limit is " << limit << " and discount is: " << discount << " returning total price: " << totalPrice << std::endl;
        return totalPrice;
    } else if (next != NULL) {
        // 直接返回下游节点的计算结果
        return next->countDiscount(b);
    } else {
        std::cout << "I am the last handler, no discount applied" << std::endl;
        return totalPrice;
    }
}
可选优化建议
  • 总价不需要在每个折扣节点重复调用b.countPrice()计算,可以作为参数在责任链中传递,减少重复计算开销
  • 如果后续需要支持多折扣叠加,只需修改逻辑为命中当前折扣后,将计算后的价格传递给下一个节点继续判断即可,不需要终止链条

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 07:54:04