Question:
Operator overloading in c++?
anonymous
2012-06-15 06:36:03 UTC
Can someone please explain in greater detail what operator overloading is, and how to do it? And if you can overload operators other than << and =. So for instance, if I want to overload the * operator so I could multiply two matrices, how would it be done?
Three answers:
anonymous
2012-06-15 06:52:18 UTC
In C you can use operators of course and their predefined function is handled by the compiler, but there is predefined code that does the operations for you. It is not magic, just that the compilers have conveniently done the work for you.





C++ allows you to "overload" the operators for you User Defined Classes. The cout and cin statements are actually part of a stream library not predefined C++ syntax. The operators for cout and cin have been overloaded.



Although the syntax for overloading operators looks kind of strange, you essentially are writing a function. As for matrix multiplication, it would depend on what your Class looks like of course.



Here is an example:

http://cboard.cprogramming.com/cplusplus-programming/67007-*operator-overloading-scalar-matrix-multiplication.html
?
2016-12-13 13:09:40 UTC
Operator overloading is under polymorphism a undeniable characteristic in C++. on a similar time as the operators in C have accepted which skill operator overloading in C++ enables us to overload the operator to supply the particular consumer defined function to the operator. Syntax is going like this operator x(arguments) { function } the place x is an operator operator overloading is often used to function the products applying operators instead of working their contributors.
Paul
2012-06-15 07:02:59 UTC
matrix operator* (matrix,matrix ); //this is the prototype typically included in the header files with the rest of the function prototypes.



You can change the * to any other operator and change the return variable accordingly. So basically when your code encounters



matrixa * matrixb it will call the function matrix operator* (matrix,matrix ) So return variable type is key.



You could for experiments sake make an operator overload which simply does.



int operator*(matrix A, matrixB){

return 2;

}



Though it has little practice, and as operator overloading is essentially functions they can call other functions from the header files and can be applied to function overloading. so you can have a second operator overload like the following.



matrix operator* (matrix,int ) which can multiply the matrix by a number.



Hope this helps


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...