c# - Operator overloading question -
suppose have class:
public class vector { public float x { get; set; } public vector(float xvalue) { x = xvalue; } public static vector operator +(vector v1, vector v2) { return new vector(v1.x + v2.x); } } have derived class:
public class myvector : vector { public static myvector operator +(myvector v1, myvector v2) { return new myvector(v1.x + v2.x); } public myvector(float xvalue):base(xvalue) { } } no if execute folowing code:
vector v1 = new myvector(10); //type myvector vector v2 = new myvector(20); //type myvector vector v3 = v1 + v2; //executed operator of vector class here executed vector's + operator, type of v1 , v2 myvector, v3 vector type @ point.
why happens?
because type of variables v1 , v2 vector, not myvector. operator overloads static methods resolved compiler @ compile-time, not @ runtime; cannot overridden.
v1 , v2 have typed myvector compiler select overload defined in myvector class.
optionally, define method public virtual vector add(vector other) on vector class , have myvector override it. call method operator+ method of vector , work expected. (myvector not need define operator+ itself.)
Comments
Post a Comment