Clas car {
Public:
Car(int,int,int,int);
Int Engine;
Int maxSpeed;
int HorsePower;
};
car::car(int a, int b, int c)
{
engine = a;
maxSpeed = b;
Horsepower = c;
// in my main I would have ..
car Opel (2,2,2);
car Ferrari (99,99,2);
// and by doing opel == ferarri => it should say which car has the better engine,maxspeed,horsepower..
}
I am a bit lost on how to overload operator, and it would help me alot, if someone could tell how to do it.. I understand the concept of using and why it used, but how someone would do, that ....
Note that in C++, case matters.
In your example, "Class" and "Public" and "Int" are not recognized as keywords.
They must be written as class, public and int respectively.
// ...
booloperator == (car lhs, car rhs) // left hand side, right hand side
{
// do the comparisons and "cout" what you want
// and at the end...
if (/* cars are equal */)
returntrue;
returnfalse; // if cars are not equal
}
int main()
{
car lhs(2, 2, 2), rhs(99, 99, 2);
lhs == rhs; // operator== will be called
// the above is a shorthand for
operator==(lhs, rhs);
}
You can also write the operator== as a member function, but in general you shouldn't do that because it requires the lhs to be the class in question (in this case, car) and this can be a limitation.
class car
{
// ...
booloperator == (car rhs) const
{
// lhs is implied and it's the current object
// otherwise, same as in the previous example
}
};
int main()
{
car lhs(2, 2, 2), rhs(99, 99, 2);
lhs == rhs; // car::operator== will be called
// the above is a shorthand for
lhs.operator==(rhs);
}
where and how would you place it .. how would you write it in the class.. i know it is a boolean operation, but how would it be for other operations...
where and how would you place it .. how would you write it in the class.. i know it is a boolean operation, but how would it be for other operations...
I would write it as a non-member overload (as in the first example).
As for other operations... what exactly do you mean?
Did you read the Wikipedia article for other operators besides operator== that you can overload?
If you cannot use the information in the Wikipedia article, it may be a sign that you are not ready yet to do this, and must spend more time learning C++. http://www.cplusplus.com/doc/tutorial/
A hint:
1 2
car operator + (car lhs, car rhs);
car operator - (car lhs, car rhs);