两个具有转换方法的类

Two classes with conversion methods

本文关键字:转换方法 两个      更新时间:2023-10-16

我在C++中有两个矩阵类,它们继承自同一个基类MatrixType。它们使用不同的方法来存储稀疏矩阵,并且是类模板,因为它们的条目可能属于不同的类型。

每个矩阵类型都应该有一个允许转换为另一种类型的方法。问题是,如果我在 MatrixCOO 类中声明toCRS,则参数的MatricCRS类型仍未定义。如何解决这个问题?

class MatrixType { /*...*/ };
template<typename Scalar>
class MatrixCOO {
    // Private stuff...
public:
    // Public stuff...
    void toCRS(MatrixCRS & target) { // Issue is here: MatrixCRS is undefined
        // Fill target with elements from *this
    }
}

template<typename Scalar>
class MatrixCRS {
    // Private stuff...
public:
    // Public stuff...
    void toCOO(MatrixCOO & target) {
        // Fill target with elements from *this
    }
}

PS:在我的理解中,即使我在MatrixCOO之前声明类MatrixCRS,在声明MatrixCRS::toCOO (MatrixCOO &)时仍然会遇到同样的问题。

向前声明一个,声明两个,定义需要两个类定义的函数:

class MatrixType { /*...*/ };
template<typename Scalar> class MatrixCRS; // Forward declaration
template<typename Scalar>
class MatrixCOO {
    // Private stuff...
public:
    // Public stuff...
    void toCRS(MatrixCRS<Scalar>& target); // Just declare the method
};
template<typename Scalar>
class MatrixCRS {
    // Private stuff...
public:
    // Public stuff...
    void toCOO(MatrixCOO<Scalar>& target) {
        // ...
    }
};
// Implementation, we have both class definitions
template<typename Scalar>
void MatrixCOO<Scalar>::toCRS(MatrixCRS<Scalar> & target)
{
    // ...
}