Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Operator operloading in C# via a custom Vector3 class

    • 0
    • 5
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 722
    Comment on it
    1. using System ;
    2. class MyVector3{
    3.     public float X {get; set;}
    4.     public float Y {get; set;}
    5.     public float Z {get; set;}
    6.  
    7.     
    8.     public MyVector3(float x, float y, float z){
    9.         X = x ;
    10.         Y = y ;
    11.         Z = z ;
    12.     }    
    13.     public static MyVector3 operator+ (MyVector3 vec1, MyVector3 vec2){
    14.         return new MyVector3( vec1.X +vec2.X , vec1.Y +vec2.Y, vec1.Z +vec2.Z) ;
    15.     }
    16.  
    17.     public static MyVector3 operator* (MyVector3 vec, float fact){
    18.         return new MyVector3( vec.X * fact , vec.Y*fact, vec.Z*fact) ;
    19.     }
    20.  
    21.     public override string ToString(){
    22.         return string.Format("({0}, {1}, {2})", this.X, this.Y, this.Z);
    23.     }
    24. }
    25. class Program{
    26.     static void Main(){
    27.         MyVector3 vec1 = new MyVector3(1, 2, 3) ;    
    28.         MyVector3 vec2 = new MyVector3(1, 2, 3) ;    
    29.         MyVector3 vec3 = vec1 + vec2 ;
    30.         MyVector3 vec4 = vec1 * 10 ;
    31.         Console.WriteLine( vec3 +" Addition") ;
    32.         Console.WriteLine( vec4 + "Multiplication") ;
    33.         Console.WriteLine( vec2 ) ;
    34.  
    35.         
    36.     }
    37. }

    Hi guys , this time it's c# .... operator overloading mechanism.....

    I've tried to simulate Vector 3 class. Which can be used to simulate a 3D axis system And this class includes addition and scalar multiplication of Vector3 , along with function ToString() overriding of Object class...

    The main point regarding it is that between 'operator' keyword and operator(+, -, >, <) to be overloaded there is no space and you need to declare it via. 'public' and 'static' access specifiers.

    Hope it's informative . Cheers!!!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: