<<
연산자를 올바르게 오버로드하고 있는지 확실하지 않습니다. 다음 코드는 문제없이 컴파일되지만 예상되는 출력을 생성하지 않습니다.<< 연산자로 결과가 출력되지 않습니다.
#include <iostream>
#include "Matrix.h"
template<class T>
std::ostream& operator<<(std::ostream &out, const matrix<T> &A)
{
for(int ii = 0; ii << A.size(1); ii++)
{
for(int jj = 0; jj < A.size(2); jj++)
{
out << A(ii,jj) << " ";
}
out << std::endl;
}
return out;
}
int main(int argc, char** argv)
{
matrix<double> A = {{1.0, 2.0},{1.0,-1.0}};
cout << "\"" << A << "\"\n";
return 0;
}
유일한 출력은 다음과 같습니다 ""
Matrix.h 루프에 대한 첫 번째에서
template<class T>
class matrix
{
public:
matrix(int rows, int cols);
matrix(const std::initializer_list<std::initializer_list<T>>& lst);
T& operator()(int i, int j);
T operator()(int i, int j) const;
int size(int n) const;
private:
int mRows;
int mCols;
std::vector<T> mData;
};
template<class T>
matrix<T>::matrix(int rows, int cols)
: mRows(rows),
mCols(cols),
mData(rows * cols)
{
}
template<class T>
matrix<T>::matrix(const std::initializer_list<std::initializer_list<T> >& lst)
: matrix(lst.size(), lst.size() ? lst.begin()->size() : 0)
{
int ii = 0, jj = 0;
for(const auto& l : lst)
{
for(const auto& v : l)
{
mData[ii*mCols + jj] = v;
jj++;
}
jj = 0;
ii++;
}
}
template<class T>
T& matrix<T>::operator()(int i, int j)
{
return mData[i*mCols + j];
}
template<class T>
T matrix<T>::operator()(int i, int j) const
{
return mData[i*mCols + j];
}
template<class T>
int matrix<T>::size(int n) const
{
if(n == 1)
{
return mRows;
}
else if(n == 2)
{
return mCols;
}
}
operator() (int, int)도 오버로드 했습니까? – jpm
@jpm 만약'operator()'가 오버로드되지 않았다면, 컴파일되지 않을 것이지만, 코드는 컴파일됩니다. –
제 잘못입니다. 나는 또한 1과 2가 size() (열거 형이 더 좋을 것임)에게주는 올바른 값인지 그리고 크기가 유효하지 않은 입력에서 큰소리로 또는 조용히 실패하는지 묻는 것은 어리석은 일이라고 생각합니다. – jpm