c++ - 具有转换方法的两个类

标签 c++ oop inheritance

我在 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/

相关文章:

c++ - 在 C++ 中使用 eigen3 进行继承和转换

c++ - C++ append_node 中 rapidXml 的奇怪结果

javascript - 为什么这个 JavaScript OO 是错误的?

php - 在构造函数中返回值以避免代码重复

Ruby 模块和 Module#append_features 解释

inheritance - 理解swift语言中的去初始化和继承

c++ - 使用模板继承影子继承成员

javascript - 编译在线 html 表单上提交的代码并使用 gcc 处理它的过程

c++ - boost::coroutine2 与 CoroutineTS

python 将方法从 classB 作为参数传递给 classA,然后从传递的 classB 方法调用 classA 中的方法