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

C++ objects being upcast to base class; cannot call derived methods

我在 C++ 中有一个 class 个对象和一个 struct 个对象。 struct 负责使用 CSV 文件中的数据填充 class。 所以这个扩展是当我创建派生 class 时,我还创建了一个派生结构,可以正确填充这个相似但不同的派生 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);}
};

结构随后被另一个执行文件读取的对象使用,并且return将多态结构提供给用户;

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

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

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

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?

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

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);

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