我在 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)
{
// ...
}
关于c++ - 具有转换方法的两个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46695336/