overloading << only prints out address

I want my display method to show up, but I only get an address that the values are stored in.

input values are 2 rows, 2 cols with the values of 2 2 3 5.
The display method has the following: rows, cols, value
The display should be:
0 0 2
0 1 2
1 0 3
1 1 5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
void SparseMat<T>::setSpRow(int k, int r, int c, T& v) {

    myMat->push_back(SpRow<T>());

    myMat->at(k).setRow(r);

    myMat->at(k).setCol(c);

    myMat->at(k).setValue(v);

}

template <class T>

void SparseMat<T>::display() {

    for (int i = 0; i < const_cast<int>(myMat->size()); i++) {

        myMat->at(i).display();
    }

}

template <class T>
ostream& operator<<(ostream& os, const SparseMat<T>& mat) {

    os << mat.display();
    return os;
}
Last edited on
I'm saddened that that even compiles for you, because you're trying to pass the result of a void function into your ostream.

os << mat.display();
mat.display() returns void (that is, it doesn't return anything).
Perhaps just trying calling "mat.display();".

But this brings up another issue: Your functions aren't set up to have the output parameterized to a chosen output stream.
Line 19: you are printing each individual row here, right? But what output stream are you displaying it *to*.

I suggest doing something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template <class T>
void SparseMat<T>::display(std::ostream& os) {

    for (int i = 0; i < const_cast<int>(myMat->size()); i++) {

        myMat->at(i).display(os);
    }

}

template <class T>
ostream& operator<<(ostream& os, const SparseMat<T>& mat) {

    mat.display(os);
    return os;
}


I don't see the definition of the SpRow.display() function, but basically any instances of "cout" you have should be replaced by the os object.


Also, you should usually avoid doing things like const_cast unless absolutely necessary. You can fix this by making your size() function const.
1
2
3
4
template <class T>
int SparseMat<T>::size() const {
    return my_size_variable;
}

(Actually, I'm not sure why you are doing the const cast there at all, it doesn't look necessary).
Last edited on
Topic archived. No new replies allowed.