0

How can i maintain operator's precedence order while overloading "+" and "*" in a class? e.g. I want same result on the calculation of following objects:
d=a+b*c;
d=c*a+b;
Please help!

Also tell me why simple constructor is able to call static data in a class?

4
Contributors
5
Replies
7
Views
7 Years
Discussion Span
Last Post by Geekitygeek
0

Hi sumit21amig, welcome!
Don't know what you are getting at here. * ALWAYS takes precedence over +. That is just standard math. The formulas you give will only have the same result if a,b and c have the same value or some of them are zero.
Static data are always available even to a simple constructor.

Edited by ddanbe: n/a

0

of course we have BODMAS rule of arithmetic which is quite applicable with integer, float, double and etc but the behavior of arithmetic operators into the context of class/object is defined by programmer to the compiler.
So, how this precedence/BODMAS is applied in a class?
I hope i am clear.

0

Most of the time you don't have to bother about operator overloading in C#. The compiler is even smart enough to figure out that a string + an integer ends in a string with the number appended. The C# compiler, like any other compiler I ever used always used the BODMAS rule as you call it. If you want to change the order of calculation use brackets.
But if the expressions d=a+b*c; and d=c*a+b; always have to resolve to the same value you have to design your own math I guess.

1

According to some quick google searches (google makes me look so smart!) in "ECMA-334: 14.2.2 Operator overloading" there is a line that reads "User-defined operator declarations cannot modify the syntax, precedence, or associativity of an operator." So, if I understand that correctly (I'm not done with my Red Bull, so anyone out there with knowledge please reply) you can't change the precedence of operators. For a fun test, derive a class from Integer and overload * and + by swapping them (make * actually add, and + multiply), then try to solve

MyInteger two = 2, three = 3, four = 4; MyInteger X = two * three + four;
Votes + Comments
He that's a nice point of view! :)
0

How can i maintain operator's precedence order while overloading "+" and "*" in a class? e.g. I want same result on the calculation of following objects:
d=a+b*c;
d=c*a+b;
Please help!

Also tell me why simple constructor is able to call static data in a class?

As ddanbe pointed out, multiplication takes precedance so your equations are calculated as:

d = a + (b*c);
d = (c*a) + b;

You would need to enclose parts in brackets if you want them to be calculated prior to the multiplication:
d = (a + b) * c;
d = c * (a + b);

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.