OSE
OSE

Reputation: 1026

Overloading << operator results in no output

I am not sure if I am correctly overloading the << operator. The following code compiles without problem but does not produce the expected output.

#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;
}

The only output is: ""

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;
    }
}

Upvotes: 0

Views: 99

Answers (1)

Drew McGowen
Drew McGowen

Reputation: 11706

In your first for loop, you have:

for(int ii = 0; ii << A.size(1); ii++)
                   ^

That should be a single < character:

for(int ii = 0; ii < A.size(1); ii++)
                   ^

The reason why it wasn't doing anything is because the original loop resulted in a condition of 0 << A.size(1), which is 0, or false; thus, the outer loop is never executed.

Upvotes: 6

Related Questions