You need to enable JavaScript to run this app. C++ 借助类继承统一输入类型的函数映射map编译失败问题
优惠活动
大模型
产品
解决方案
定价
更多

C++ 借助类继承统一输入类型的函数映射map编译失败问题

核心问题根因
  • 直接将派生类对象赋值给父类类型的map值,会触发对象切片:派生类独有的边长、半径等属性会被直接截断丢弃,后续计算根本拿不到这些专属字段
  • 不同参数签名的函数无法直接存入同类型的可调用对象map:编译器只会做静态签名校验,不会自动将传入的父类参数转换为各子程序需要的派生类类型
落地实现方法

1. 解决对象切片问题

放弃在map中直接存储父类值,改为存储指向父类的智能指针,从根本上避免切片:

  • 定义map的value类型为std::unique_ptr<SuperParentClass>,所有派生类对象在堆上构造,通过智能指针管理生命周期
  • 必须给SuperParentClass添加虚析构函数,让父类成为多态类型,才能支持后续的类型安全转换

2. 解决函数签名不匹配问题

统一可调用对象的签名为「接收指向父类的裸指针、返回int」,给每个业务函数包一层适配逻辑:

  • 适配层接收到传入的父类指针后,通过dynamic_cast做运行时类型校验,确认类型匹配后再调用对应的业务子程序
  • 类型不匹配时直接返回错误值,避免非法内存访问
关键修改要点
  • 给SuperParentClass补充虚析构函数,否则无法使用dynamic_cast做安全类型转换
  • 存入派生类对象时,用std::make_unique构造堆上实例,不要在栈上构造后赋值给父类类型
  • 修改派生类专属属性时,先通过dynamic_cast拿到对应派生类的指针,再修改字段,不能直接用基类指针访问派生类属性
完整可运行代码
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <math.h> 


class SuperParentClass
{
public:
    std::string nameClass;
    virtual ~SuperParentClass() = default;
};

class ChildClassRectangle : public SuperParentClass
{
public:
    int longueur=2;
    int largeur=2;
};

class ChildClassCircle : public SuperParentClass
{
public:
    int radius=2;
};

int areaRect(ChildClassRectangle rect)
{
    std::cout << "areaRect "<< rect.largeur*rect.longueur << std::endl;
    return 0;
}

int areaCircle(ChildClassCircle circ)
{
    std::cout << "areaCircle "<< 3.14*pow(circ.radius,2) << std::endl;
    return 0;
}


int main()
{  
    std::cout << "TEST " << std::endl;
    std::map<std::string, std::unique_ptr<SuperParentClass>> mapObject;
    // 初始化Circle对象
    auto circ = std::make_unique<ChildClassCircle>();
    circ->radius = 2;
    mapObject["Circle"] = std::move(circ);
    // 初始化Rectangle对象
    auto rect = std::make_unique<ChildClassRectangle>();
    rect->longueur = 1;
    rect->largeur = 3;
    mapObject["Rectangle"] = std::move(rect);
    
    using CallFunc = std::function<int(SuperParentClass*)>;
    std::map<std::string, CallFunc> mapFunction;
    
    // 存入适配后的可调用对象
    mapFunction["Circle"] = [](SuperParentClass* base_ptr) {
        auto circ_ptr = dynamic_cast<ChildClassCircle*>(base_ptr);
        if (!circ_ptr) return -1;
        return areaCircle(*circ_ptr);
    };
    mapFunction["Rectangle"] = [](SuperParentClass* base_ptr) {
        auto rect_ptr = dynamic_cast<ChildClassRectangle*>(base_ptr);
        if (!rect_ptr) return -1;
        return areaRect(*rect_ptr);
    };

    // 首次调用计算
    mapFunction["Circle"](mapObject["Circle"].get());
    // 修改Rectangle的专属边长属性
    auto mod_rect_ptr = dynamic_cast<ChildClassRectangle*>(mapObject["Rectangle"].get());
    mod_rect_ptr->largeur = 4;
    // 修改后再次调用计算
    mapFunction["Rectangle"](mapObject["Rectangle"].get());
    return 0;
};

内容的提问来源于stack exchange,提问作者R. N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 12:15:07