gpt4 book ai didi

C++ 对象被向上转换为基类;不能调用派生方法

转载 作者:行者123 更新时间:2023-11-30 05:18:40 35 4
gpt4 key购买 nike

我在 C++ 中有一个 class 对象和一个 struct 对象。 struct 负责使用 CSV 文件中的数据填充 class。因此,扩展是当我创建一个派生类时,我还创建了一个派生结构,该结构将正确填充这个相似但不同的派生类。

struct BaseStruct {
double var = 0;
vector<double> vectorA;
virtual BaseClass^ generateClass() {return gcnew BaseClass(this->var, this->vectorA);}
};
struct DerivedStruct : BaseStruct {
vector<double> vectorB;
virtual BaseClass^ generateClass() override {return gcnew ChildClass(this->var, this->vectorA, this->vectorB);}
};

然后,该结构被另一个执行文件读取的对象使用,并将多态结构返回给用户;

BaseStruct FileReader::GetSetupStruct(String^ parameter)
{
BaseStruct retval; //Struct to be passed back
retval = (boolLogicCondition) ? BaseStruct() : DerivedStruct(); //Should return correct type of struct
return retval;
}

但是,当我尝试使用下面的代码时,通过将其作为基类引用,它会自动恢复为基类(失去额外的 vectorB 属性)及其多态性。

我怀疑它失去了派生状态,因为 a) 当我从三元运算符返回时,它在局部变量窗口中的类型发生了变化 b) setupStruct.generateClass() 只执行基类方法

BaseStruct setupStruct = FileReader::GetSetupStruct(parameter);//Returns struct - type should depend on parameters
Signal^ mySignal = setupStruct.generateClass(); //Should run either derived or base method

我如何使用这两个结构并在运行时生成正确的类型,同时保持多态性质而不将其向上转换为基类型?

最佳答案

在这段代码中:

BaseStruct retval; //Struct to be passed back
retval = (boolLogicCondition) ? BaseStruct() : DerivedStruct();
  • 选择运算符产生一个,而不是一个引用。

  • BaseStruct 类型的 retval 的赋值,无论如何都会将结果切片到 BaseStruct


回复

How can I use these two structs and generate the correct type at run time, but maintain the polymorphism nature without it being upcasted to the base type?

…获得多态行为的一种方法是返回指向工厂实例的指针,而不是按值返回:

auto FileReader::GetSetupStruct(String^ parameter)
-> std::unique_ptr<BaseStruct>
{
if( boolLogicCondition )
{
return std::make_unique<BaseStruct>();
}
else
{
return std::make_unique<DerivedStruct>();
}
}

免责声明:即兴代码甚至连编译器都没有看一眼。


在其他上下文中,选择运算符可以产生一个引用。例如,对于同一类型的两个变量 ab,您可以这样做

auto* p = &(condition? a : b);

但在上面的代码中,可供选择的子表达式都是右值表达式,或者更通俗地说,是“值”表达式,您无法对其应用内置的 & 地址运算符。

关于C++ 对象被向上转换为基类;不能调用派生方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41554088/

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