What does it mean to have operator as a prefix to >>, or != or ==, or any of the other operands?
Printable View
What does it mean to have operator as a prefix to >>, or != or ==, or any of the other operands?
You mean things like:
It's defining a custom operator (i.e. it's a function).Code:bool operator==( const Obj& lhs, const Obj& rhs );
So that you can do things like this:
or this:Code:std::cout << "Hello World." << std::endl;
Generally, when defining operators for classes, try to stay true to the original meaning of the operator. (ie, '+' means 'add')Code:std::string str = std::string("Hello") + " World.";
[QUOTE=Cactus_Hugger;775139]So that you can do things like this:
or this:Code:std::cout << "Hello World." << std::endl;
So its like, you could assign them in a different way, or use operators in a different way for classes???Code:std::string str = std::string("Hello") + " World.";
Just like Cactus_Hugger said, you usually need to overload certain operators of an object (e.g. the copy constructor / '=', or comparisons like <, ==, or >). So, if it's not overloaded, it won't do what you want it to do.
E.g. a class 'Matrix' to define a 3d matrix. If you haven't overloaded the 'equal to' operator and call this:
It would mostly returned a false because it wouldn't compare the values of the x, y, z. Now, if you do an operator overload like:Code:class Matrix
{
private:
float x;
float y;
float z;
...
}
Matrix a, b;
....
if (a == b)
{
...
}
It would compare between two matrices just like you wanted it to.Code:class Matrix
{
private:
float x;
float y;
float z;
public:
bool operator=(const Matrix &operand)
{
return ((this->x == operand->x) &&
(this->y == operand->y) &&
(this->z == operand->z) &&);
}
}
The type is const Matrix& (this is why I prefer to type const Matrix& something and not const Matrix &something).
Essentially, it takes a (const) reference (the &) to an object of type Matrix.
Const reference means it cannot modify the object.
But it can be anything you like. So long as it makes sense.