c ++将类的实例转换为另一个

时间:2017-05-02 08:35:54

标签: c++ inheritance type-conversion

我想知道是否有办法在c ++中编写类转换 我不是在谈论任何形式的type_casting,而是克隆并将实例转换为另一个实例。

如果我有这段代码:

class BaseClass
{
    string baseData;
};

class DerivedClassB : public BaseClass
{
    int intData;
};

class DerivedClassA : public BaseClass
{
    float floatData;
};

假设我有一个DerivedClassA的实例,我想转换'那个实例到DerivedClassB甚至BaseClass我都不关心' floatData'的丢失,只要' baseData'保留BaseClass

我可以实现从任何类型到任何类型的转换吗?

BaseClass -> DerivedClassA
DerivedClassA -> DerivedClassB
DerivedClassB -> BaseClass 

我如何实现这样的功能?

非常感谢你的启蒙。

1 个答案:

答案 0 :(得分:1)

  

我可以实现从任何类型到任何类型的转换吗?

嗯,是的,这是//Forward declaration class BaseClass; class DerivedClassB; class DerivedClassA; class BaseClass { //Converting constructor: DerivedClassB -> BaseClass BaseClass(const DerivedClassB&); BaseClass() = default; string baseData; }; class DerivedClassB : public BaseClass { //Converting constructor: DerivedClassA -> DerivedClassB DerivedClassB(const DerivedClassA&); DerivedClassB() = default; int intData; }; class DerivedClassA : public BaseClass { //Converting constructor: BaseClass -> DerivedClassA DerivedClassA(const BaseClass&); DerivedClassA() = default; float floatData; }; // -------------------------- //Implement them out of class 对的目的吗? 如果您中断strict aliasing rules

,您很可能会调用未定义的行为
  

我如何实现这样的功能?

对于您的用例,您可以只提供Converting Constructor

for (int curCol = 0; curCol < numRows; ++curCol){     //Long Loop
        int lb = csc_colIndices[curCol];
        int ub = csc_colIndices[curCol + 1];

        // push back the diagonal value to L matrix
        vec_L_val[curCol].push_back(1.0f);
        vec_L_indices[curCol].push_back(curCol);

        for (int curIndex = lb; curIndex < ub; ++curIndex){
            int curRow = csc_indices[curIndex];
            float curVal = csc_val[curIndex];

            if (!Equal(curVal, 0) && curRow <= curCol){// U entry
                vec_U_val[curCol].push_back(curVal);
                vec_U_indices[curCol].push_back(curRow);
            }
            else if (!Equal(curVal, 0) && curRow > curCol){// L entry
                vec_L_val[curCol].push_back(curVal);
                vec_L_indices[curCol].push_back(curRow);
            }
        }
    }