+ 4
Why should you override operators?
I learned Operator overriding from SoloLearn. I am little confused about it. In which situation you will override operators?
6 odpowiedzi
+ 3
here is an example that you may want to check to see difference or understand the meanings of overriding and overloading https://code.sololearn.com/c0awDMpDLukF/?ref=app
+ 2
An Example is already in the course (C#)..
let's say you have a class call Cube.
class Cube {
private int cap=0;
public Cube (int w, int l,int h){
this.cap = w*l*h;
}
}
lets say you want to get the sum of 2 Cubes(2 instances of Cube class)
Cube(2,3,1) + Cube(3,2,1)
so you can override + (addition) to do the task.
+ 1
The answer is simple: for added convenience. One really good example, besides overloaded operator>> / operator<< from <iostream>, is overloaded operator/ from boost:: filesystem (way beyond the scope of this site) for string concatenation of file paths.
+ 1
alright thanks all
0
In resume the purpose is to simplify code. How? In the example of the Cube, you could create a method with the name CubeSum, which would perform the sum of 2 objects of the class Cube.
In the Main class to make sum of Cube a and b the code would be like:
Cube c = a.CubeSum(b)
But instead we can use the operator +, and to do that we overload the value of + in C# to make something different.
Cube c = a+b
Another good example is with matrix, if you create your own matrix class, it would be very useful to create an operator overloading of the sum, multiplications, etc. between matrix objects.
0
hi