• Advertisement
Sign in to follow this  

Can't overload the operator

This topic is 3905 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

As the title says, I'm having a problem overloading the << operator. It occurs in this header:
#ifndef COORD_H
#define COORD_H

// Class Coord
// Descr:    A coordinate.
// Members:  value -> The value of the coordinate.
// Func:    -Assignment through a Coord and an integer.
//          -Equality check based on the values of the coordinates.

#include <iostream>

class Coord {
	  // Constructor: initializes 'value'
	Coord(int v = 0): value(v) {}
	  // Copy constructor
	Coord(const Coord& c);
	  // Assigns 'c.value' to 'value'
	Coord& operator=(const Coord& c);
	  // Assigns 'i' to 'value'
	Coord& operator=(const int i);
	  // Returns whether 'c.value' equals 'value'
	bool operator==(const Coord& c) const;    
	  // Writes 'value' into 'os' (for testing purposes)
	std::ostream& operator<<(std::ostream& os, const Coord& c) const;   

	  // Getter for 'value'
	int Value() const;
	  // Setter for 'value'
	void SetValue(int i);

	int value;


When I try to compile, I get the following error: error C2804: binary 'operator <<' has too many parameters I understand what the error message is telling me, but I don't get why it's even there. My book appears to overload the operator in the exact same way. So why does this error occur and how do I go about fixing it?

Share this post

Link to post
Share on other sites
I doubt your book has it as a class member, but more likely as a free function. As it is, your current overload is taking 3 arguments, one implicit and two explicit.

Share this post

Link to post
Share on other sites
You must make it a free function, not a member fuction. It cannot be a member function of the Coord class, because it will be called on the stream object.

foo << myCoord

The above is equal to one of these two, depending on which one is defined.

foo.operator <<(myCoord); // (1)
operator <<(foo, myCoord); // (2)

Since (1) requires modification of the stream class, you cannot do it that way. Only the free function form remains. Move the declaration you have at the moment out of the class, and make it friend if necessary.

edit: Some fixes... and too slow.

Share this post

Link to post
Share on other sites
You were right. Making it a free function solved the problem.
Thank you.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement