gpt4 book ai didi

C++ MatLab 类构造函数重载

转载 作者:行者123 更新时间:2023-11-30 02:01:17 26 4
gpt4 key购买 nike

我有一个 Sparse_Matrix 类,可以让我高效地处理稀疏矩阵。

我想通过使用特定(惯用)关键字(如 Upper、Identity 等)来实例化特定矩阵。

这是我的类声明(命名空间矩阵)

template <typename T>
class Sparse_Matrix
{

private:
int rows;
int cols;
std::vector<int> col;
std::vector<int> row;
std::vector<T> value;
...

有没有办法得到预初始化的对象?

 Sparse_Matrix<int> = Eye(3);

将返回一个 3×3 单位矩阵。

我看过构造函数惯用语,但那些需要一些与我的类不兼容的软静态类型(尽管我愿意接受建议)。

我也试过这段代码:

template <typename T>
Sparse_Matrix<T> Eye(int size)
{
Sparse_Matrix<T> ma;
ma.IdentityMatrix(size);
std::cout << "Eye!" << std::endl;
return ma;
}

...

Sparse_Matrix<int> blah = Eye(10);

但无济于事。

谢谢,

阳光男孩纽约

最佳答案

在 C++ 中只有一个地方可以根据表达式的使用方式推导出模板参数:用户定义的转换运算符。

struct Eye
{
int size;
explicit Eye(int requestedSize) : size(requestedSize) {}

template<typename T>
operator SparseMatrix<T>() const { SparseMatrix<T> ma; ma.IdentityMatrix(size); return ma; }
};

现在你可以写了

Sparse_Matrix<int> blah = Eye(10);

关于C++ MatLab 类构造函数重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14270768/

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