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
    • 630
    Comment on it
    using System ; 
    class MyVector3{
    	public float X {get; set;}
    	public float Y {get; set;}
    	public float Z {get; set;}
    
    	
    	public MyVector3(float x, float y, float z){
    		X = x ;
    		Y = y ;
    		Z = z ;
    	}	
    	public static MyVector3 operator+ (MyVector3 vec1, MyVector3 vec2){
    		return new MyVector3( vec1.X +vec2.X , vec1.Y +vec2.Y, vec1.Z +vec2.Z) ;
    	} 
    
    	public static MyVector3 operator* (MyVector3 vec, float fact){
    		return new MyVector3( vec.X * fact , vec.Y*fact, vec.Z*fact) ;
    	} 
    
    	public override string ToString(){
    		return string.Format("({0}, {1}, {2})", this.X, this.Y, this.Z);
    	}
    }
    class Program{
    	static void Main(){
    		MyVector3 vec1 = new MyVector3(1, 2, 3) ;	
    		MyVector3 vec2 = new MyVector3(1, 2, 3) ;	
    		MyVector3 vec3 = vec1 + vec2 ;
    		MyVector3 vec4 = vec1 * 10 ;
    		Console.WriteLine( vec3 +" Addition") ;
    		Console.WriteLine( vec4 + "Multiplication") ;
    		Console.WriteLine( vec2 ) ;
    
    		
    	}
    }

    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
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: