gpt4 book ai didi

c++ - 在运行时如何确定非多态类型的实际类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:44:33 25 4
gpt4 key购买 nike

我有这样的声明:

struct InstrumentInfo
{
std::string Name;
TradingStatus Status;
myDecimal MinStep;
std::string ISIN;
myDecimal limit_down;
myDecimal limit_up;
};

struct FortsDerivativeInfo : InstrumentInfo
{
std::string ShortIsin;
int IsinId;
std::string CodeVcb;
myDecimal StepPrice;
int LotVolume;
myDecimal exch_pay;
};

struct StockInfo : InstrumentInfo
{
int LotSize;
};

我试过写这样的代码:

if (auto si = dynamic_cast<StockInfo*>(ii))
{
LOT_SIZE = si->LotSize;
}
else
{
LOT_SIZE = 1;
}

这无法编译,我收到“错误 C2683:‘dynamic_cast’:‘InstrumentInfo’不是多态类型”。我该如何解决这个错误?

如果我将 dynamic_cast 替换为 static_cast 代码编译,但由于 static_cast 不执行任何运行时检查,恐怕这不会工作?

最佳答案

运行时类型信息仅适用于至少具有一个虚函数的类型(即“多态类型”)。使 dynamic_cast 工作的唯一方法是使基类型多态 - 例如,通过声明其析构函数 virtual

更好的方法是完全消除对转换的需要 - 例如,通过创建一个虚拟的 lotSize 函数:

struct InstrumentInfo
{
std::string Name;
TradingStatus Status;
myDecimal MinStep;
std::string ISIN;
myDecimal limit_down;
myDecimal limit_up;
virtual int lotSize() const { return 1; }
};

struct StockInfo : InstrumentInfo
{
int LotSize;
virtual int lotSize() const { return LotSize; }
};

InstrumentInfo ii;
LOT_SIZE = ii.lotSize();

关于c++ - 在运行时如何确定非多态类型的实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23521117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com