I have some questions about a homework assignment. If someone could help me answer these questions, but also with an explanation to help me understand, I would be very appreciative. I don't really understand what functions will be called. Thanks so much.
1. What line number will be executed if we enter the code: if (mystra ==mystrb) {y = 2;}
2. What line number will be executed if we enter the code: mystra =mystrb;
3. What line number will be executed if we enter the code: mystra[2] = 'K';
4. What line number will be executed if we enter the code: ch = mystra[1];
I think it means "which operator overload would be invoked by such code".
For example, the answer to #1 is line 17. The overload for operator== would be invoked.
#include <iostream>
class vector
{
public:
int x;
int y;
vector() : x(0), y(0) {}
vector(int X, int Y) : x(X), y(Y) {}
booloperator==(vector b) // try commenting out this function and see if the "if (a == b)" still works
{
if (x == b.x && y == b.y)
returntrue;
elsereturnfalse;
}
};
int main()
{
vector a(1, 1);
vector b(1, -1);
if (a == b) // <--- this will fail if == is not implemented
std::cout << "do awesome code \n";
else
std::cout << "don't do awesome code \n";
std::cin.get();
}
now the link i gave you earlier will probably help you more but i hope this givers you a basic idea what its used for and how handy it is.
Edit:
I don't want to confuse you now. but if you feel you understand the first part continue reading. with operator overloading you don't need follow the c++ rules as in "==" does not need to be a comparator.
here is an example of "==" used for returning the bigger of the 2 vectors.
I really appreciate your explanation of operator assignment. I do understand the first block of code you wrote, but I do not understand the second block. I understand in the first segment, "==" is being changed to be able to compare vectors. I don't know what the second part is doing. Really great, nonetheless.
disturbedfuel15: i was afraid i was confusing you, i am so sorry. let me try to explain it different.
in c++ you have certain operators that you are pretty familiar with. you expect them to so certain things. well with operator overloading you can implement those operators. but what i tried to illustrate in my second example. it is possible do make them do other stuff, things you would not expect them to. like i did.
but for now you can forget my second example and look back on it when you know a little more c++.
it is possible do make them do other stuff, things you would not expect them to. like i did.
You are correct this is certainly possible, but it should absolutely be avoided.
The whole point of overloading operators is to make code more intuitive. IE: do something you'd expect it to.
If you overload an operator to do something other what what you'd expect... or if it's not immediately and plainly obvious to anyone what an operator overload should do... then you should not overload it in that fashion.