gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:42:10 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com