Need help with overloading the stream insertion operator

I am trying to display all the content stored in one object to the screen without resorting to a member function that actually displays it for me.

Below i have use two overloaded operator functions, one that adds the values stored in one class object with another and returns the result to yet another class object.

But i am having some trouble trying to overload the insertion operator in my class. The compiler claims that there is an error in the overloaded function..

What am i doing wrong?

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <iostream>

using namespace std;

class Color
{
  int number;
  float number2;
  int *pointer;
  int num_of_elements;

public:

    Color ()
    {


    }



    Color (int n, int m)
    {
    number = n;
    number2 = m;
    num_of_elements = m;
    pointer = new int [num_of_elements];

    for (int v = 0; v < num_of_elements; v++)
        {
         pointer [v] = v;
        }
    }


    Color operator + (Color & n)
    {
        Color temp;

        temp.number = number + n.number;
        temp.number2 = number2 + n.number2;
        temp.num_of_elements = num_of_elements;
        temp.pointer = new int [num_of_elements];

        for (int x = 0; x < num_of_elements; x++)
        {
            temp.pointer[x] = pointer [x] + n.pointer[x];
        }

        return temp;
    }


   


    ostream &operator << (ostream &strm, Color &n)      //here is the error
    {

        strm << n.number << " " << n.number2 << " " << n.num_of_elements  << " ";

        return strm;
    }

       void operator ++ (int)
        {
          number++;
        }


};

int main ()
{


    Color favorite;

    Color fav[2] = {Color (6,4),
                    Color (6,4)};

    favorite = fav[0] + fav[1];

    favorite++;

 



    cout << favorite;




}
Line 27 57: needs to be a friend.

 
friend ostream &operator << (ostream &strm, Color &n) 


edit: corrected line number.
Last edited on
Ah thank you.

I understand now that overloading insertion operator needs to be a friend but..

Why does line 27 have to be a friend?

EDIT: and why does line 57 also have to be a friend?
Last edited on
That was a typo. I meant line 57, not 27. Sorry for the confusion.

Line 57 is the declaration (and implementation) of the operator << function in your class. The friend modifier needs to be on the declaration.
Last edited on
Topic archived. No new replies allowed.