【发布时间】:2020-12-02 17:36:02
【问题描述】:
我为我的矩阵类实现了一个构造函数,以使用嵌套的 std::initializer_list 进行大括号括起来的初始化。构造函数适用于主要类型:`int`、`double`;但会为“复杂”呈现错误读取。如何解决此错误阅读?
矩阵类
template <typename T> class xxx
{
public:
T *ptr;
int col, row, size;
xxx() = delete;
xxx(const int i, const int j):row(i), col(j), size(i*j)
{
ptr = new T [this->size] ;
}
xxx(const std::initializer_list< std::initializer_list<T> > s):xxx(s.size(), s.begin()->size())
{
int j = 0;
for (const auto& i : s) { std::copy (i.begin(), i.end(), ptr + j*col); ++j ; }
}
~xxx() {delete [] this->ptr;}
T operator()(const int i, const int j) const { return ptr[i*col+j]; }
};
这里添加了一个典型的输出过载来完成。
template <typename X> std::ostream& operator<<(std::ostream&p, const xxx<X>&a)
{
for (int i=0; i<a.row; i++) {
for (int j=0; j <a.col; j++) p << std::setw(6) << a(i, j);
p << std::endl;
}
return p;
}
`double` 类型的第一个测试 main() 运行良好。
#include <iostream>
#include <initializer_list>
#include <iomanip>
#include <complex>
int main()
{
xxx<double> x = {{1, 2,3,4} , {3, 4,5,6}, {5, 6,7,8} };
std::cout << x << std::endl;
}
它打印预期的内容:
$ ./a.exe
1 2 3 4
3 4 5 6
5 6 7 8
然后,我尝试另一种我感兴趣的类型,`complex`:
int main()
{
xxx< std::complex<double> > z = { {(1,2), (3,4)}, {(5,6), (7,8)} };
std::cout << z << std::endl;
}
输出错误如下:
$ ./a.exe
(2,0) (4,0)
(6,0) (8,0)
缺少想象部分,真实部分取反想象部分的值。任何想法或建议都将受到高度赞赏。
【问题讨论】:
-
你能发一个minimal reproducible example吗?没有你的
operator<<,我看不到代码的输出 -
为完整性添加了输出过载。
标签: c++ c++11 complex-numbers list-initialization