Archived

This topic is now archived and is closed to further replies.

BattleGuard

Operator overloading?!?!

Recommended Posts

Hi, I get a this error:
error C2568: '<<' : unable to resolve function overload
(on the commented line in the code) when I use this code:
//standard headers. iostream, etc...


class Box
{
public:
	Box( double alength = 1.0, double aBreadth = 1.0,double aHeight = 1.0);

	double volume() const;

	double getLength() const;
	double getBreadth() const;
	double getHeight() const;

	bool operator<(const Box& abox) const
	{
		return volume() < abox.volume();
	}

private:
	double length;
	double breadth;
	double height;
};

Box::Box(double aLength, double aBreadth, double aHeight):
length(aLength), breadth(aBreadth), height(aHeight) {}

double Box::volume() const
{
	return length*breadth*length;
}

double Box::getBreadth() const { return breadth; }
double Box::getHeight() const { return height; }
double Box::getLength() const { return length; }
int main() 
{ 
	Box one(20, 20, 20);
	Box two(20, 10, 30);

	cout << one < two ? "one has a larger volume than two" : "two has a larger volume than one"<<endl;
        // error on the cout<<... line above this line ^


} 
didn't I overload the operator correctly? Pardon me, since I'm a little new to overloading... Thanx BattleGuard
Only questions raise questions. Questions are raised by people, by curiousity, the gift of nature to all human beings. And curiosity is satisfied by answers, which in turn raise questions, which lead to answers. And this curiosity is what keeps SCIENCE alive...

Share this post


Link to post
Share on other sites
do this:

cout << ( one < two ? "one has a larger volume than two" : "two has a larger volume than one" ) << endl;

with parentheses, tried it on my Visual Studio.Net and it worked.

[edited by - alnite on July 4, 2003 12:33:53 PM]

Share this post


Link to post
Share on other sites
alnite is correct here: the << operator has a higher precedence than the < and ?: operators, so that line gets split up thus:

((cout << one) < two ) ? "one has..." : ("two has..."<<endl);

And so, it can't find an operator to insert std::endl into a char*.

Putting the parentheses where he suggests will force the compiler into splitting the statement up properly.

[edit: fixed <s]



[edited by - sbennett on July 4, 2003 12:48:07 PM]

[edited by - sbennett on July 4, 2003 12:49:00 PM]

Share this post


Link to post
Share on other sites
Thanx, alnite and sbennett. That fixed it. I didn''t look at precedence...

BattleGuard



Only questions raise questions. Questions are raised by people, by curiousity, the gift of nature to all human beings. And curiosity is satisfied by answers, which in turn raise questions, which lead to answers. And this curiosity is what keeps SCIENCE alive...

Share this post


Link to post
Share on other sites