C#源码学习之---运算符的重载

源码下载:http://dl2.csdn.net/down4/20070910/10205619937.rar
using  System;
using  System.Collections.Generic;
using  System.Text;

namespace  ConsoleApplication3
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            Vector v1, v2, v3;
            v1 
= new Vector(1.01.52.0);
            v2 
= new Vector(0.00.0-10.0);
            v3 
= v1 + v2;
            Console.WriteLine(
"v1=" + v1);
            Console.WriteLine(
"v2=" + v2);
            Console.WriteLine(
"v1+v2=" + v3);
            Console.WriteLine(
"2*v3=" + 2 * v3);
            v3 
+= v2;
            Console.WriteLine(
"v3+=v2 guves" + v3);
            v3 
= v1 * 2;
            Console.WriteLine(
"Setting v3=v1*2 gives" + v3);
            
double dot = v1 * v3;
            Console.WriteLine(
"v1*v3=" + dot);
            Console.ReadKey();


        }

      }

    
struct Vector
    
{
        
public double x, y, z;
        
public Vector(double x, double y, double z)
        
{
            
this.x = x;
            
this.y = y;
            
this.z = z;

        }

        
public Vector(Vector hs)
        
{
            
this.x = hs.x;
            
this.y = hs.y;
            
this.z = hs.z;
        }

        
public override string ToString() // ToString()方法重写;
        {
            
return "(" + x + "," + y + "," + z + ")";
        }


        
//运算符的重载;
        public static Vector operator +(Vector lhs, Vector rhs)
        
{
            Vector result 
= new Vector(lhs);
            result.x 
+= rhs.x;
            result.y 
+= rhs.y;
            result.z 
+= rhs.z;
            
return result;
        }

        
public static Vector operator *(double lhs, Vector rhs)
        
{
            
return new Vector(lhs * rhs.x, lhs * rhs.y, lhs * rhs.z);
        }

        
public static Vector operator *(Vector lhs, double rhs)
        
{
            
return new Vector(rhs * lhs.x, rhs * lhs.y, rhs * lhs.z);
        }

        
public static double operator *(Vector rhs, Vector lhs)
        
{
            
return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z;
        }

    }

 }

   
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值