| jay2tharoc (4) | |
|
First I want to put it out there that yes this is homework and no I'm not asking for it to be done for me :) For my assignment I have to create a class that simulates blocks of memory. I have to write a few member functions and overload some operators. I have +, == and = working as they should but am having some problems with some other aspects of the assignment. I am tying to overload the << operator. I am having some trouble with it and every example I can find online shows it as a friend function. I haven't seen it as a member function and I haven't figured it out yet so I am not sure how to proceed. To my understanding, a member function needs exactly one argument. I guess if anyone could point me to an example or an example of just the function signature that would help. Thanks for reading. | |
|
|
|
| Nexius (142) | |
Overload it the same way you did the others.void class_t::operator << (data_t data);
| |
|
|
|
| jay2tharoc (4) | |
| I tried something similar but I probably screwed up somewhere. Thanks :) I will keep trying. | |
|
|
|
| ne555 (4041) | |
|
> To my understanding, a member function needs exactly one argument Nope, if it is a binary operator then the `left' operand is this (the object that makes the call)so the signature just ask for one argument. > I probably screwed up somewhere Likely, if you show what you did we may help. | |
|
|
|
| jay2tharoc (4) | |||
|
Ok this is what I have. I clearly don't understand something. Hopefully I am at least kind of on track. This is the error message I get when trying to compile. For line 23 and 30. Memory.cpp:23:19: error: ‘void Memory::operator<<()’ must take exactly one argument.
| |||
|
|
|||
| ne555 (4041) | |
cout << a; if that how you intent to use it then it can't be a member functionThe message is send to the left object (cout), that's of type ostream. Either you put it as a member function of ostream, or as a global function ostream& operator<<( ostream &, const Memory & );
| |
|
|
|
| jay2tharoc (4) | |
|
Ok that's how I was going to do it originally but then I reread the assignment and it said member functions so that's how I was trying to do it.. So I guess my next question is how would I output an array in that way? If it was say a point I could just do something like this I think: ostream &operator<<( ostream &o, const Point &p) { return ( o << "X: " << p.x << "Y: " << p.y << endl ); } Would that be right? I am not sure how I would output an array because then the number of fields would vary depending on size of array. | |
|
|
|
| ne555 (4041) | |
|
You need 3 parameters: the stream, the array, the array's size. But the << is a binary operator (2 parameters) Alternatives: _ Use a centinel. Like '\0' for c-strings_ Use a container that knows its size. Like std::vector _ Use a `print()' function | |
|
|
|