算术运算符的重载

北城以北 提交于 2019-12-05 15:03:05

运算符重载的示例:Vector结构

using System;

namespace 运算符重载
{
    class Program
    {
        static void Main(string[] args)
        {
        //    Console.WriteLine("Hello World!");
        // Vector vec1,vec2,vec3;
        // vec1 = new Vector(3.0,3.0,1.0);
        // vec2 = new Vector(2.0,-4.0,-4.0);
        // vec3 = vec1 + vec2;
        // System.Console.WriteLine($"vec1 = {vec1}");
        // System.Console.WriteLine($"vec2 = {vec2}");
        // System.Console.WriteLine($"vec3 = {vec3}");

        // double dou = 7;
        // Vector vec = new Vector(1.0,2.0,3.0);
        // Vector vec2 = dou * vec;
        // Vector vec3 = vec * dou;
        // System.Console.WriteLine($"{vec2}");
        // System.Console.WriteLine($"{vec3}");

        Vector vec1,vec2,vec3;
        vec1 = new Vector(1.0,1.5,2.0);
        vec2 = new Vector(0,0,-10);
        //vec3 = vec1 + vec2;
        vec3 = vec1 * 2;
        System.Console.WriteLine($"vec1 * vec2 = {vec1*vec3}");
        }
        
    }

    //声明结构(运算符重载用于结构和类时,其工作方式时一样的。)
    struct Vector{
        public double X{get;}
        public double Y{get;}
        public double Z{get;}
        public Vector(double x,double y,double z){
            X = x;
            Y = y;
            Z = z;

        }
        public Vector(Vector vector){
            X = vector.X;
            Y = vector.Y;
            Z = vector.Z;

        }
        public override string ToString()=>$"({X},{Y},{Z})";
        //+ 的运算符重载
        public static Vector operator + (Vector left,Vector right)=>
        new Vector(left.X + right.X,left.Y + right.Y,left.Z + right.Z);
        //* 的运算符重载
        public static Vector operator *(double left,Vector right)=>
        new Vector(left*right.X,left*right.Y,left*right.Z);

        public static Vector operator *(Vector left,double right)=>right * left;

        //内积
        public static double operator *(Vector left,Vector right)=>left.X*right.X+left.Y*right.Y+left.Z*right.Z;
        

    }
     
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!