========================================運算符重載
網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)公司!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、微信平臺小程序開發(fā)、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了杜爾伯特免費建站歡迎大家使用!
-------------------------------------------------------------------------Vector.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { public struct Vector//結構和類是相似的 { public int x, y, z; public Vector(int x, int y, int z)//構造函數(shù) { this.x = x; this.y = y; this.z = z; } public Vector(Vector v)//構造函數(shù) { this.x = v.x; this.y = v.y; this.z = v.z; } public override string ToString()//重載tostring方法 { return string.Format("x:{0};y:{1};z:{2}", x, y, z); } //重載運算符 //第一個參數(shù)是運算符左邊的,第二個參數(shù)是運算符右邊的 //+ - * / 是一樣的 public static Vector operator *(Vector lhs, Vector rhs) { Vector v = new Vector(lhs); v.x *= rhs.x; v.y *= rhs.y; v.z *= rhs.z; return v; } } }
-------------------------------------------------------------------------主程序
Vector v1 = new Vector(1, 2, 3); Vector v2 = new Vector(3, 2, 1); Console.WriteLine((v1 * v2).ToString());//輸出x:3;y:4;z:3 Console.ReadKey();
========================================比較運算符重載
-------------------------------------------------------------------------Vector.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication4 { public struct Vector//結構和類是相似的 { public int x, y, z; public Vector(int x, int y, int z)//構造函數(shù) { this.x = x; this.y = y; this.z = z; } public Vector(Vector v)//構造函數(shù) { this.x = v.x; this.y = v.y; this.z = v.z; } public override string ToString()//重載tostring方法 { return string.Format("x:{0};y:{1};z:{2}", x, y, z); } //重載比較運算符 //== 與!= 需成對出現(xiàn) //> 與 < 需成對出現(xiàn) //>= 與 <= 需成對出現(xiàn) public static bool operator ==(Vector lhs, Vector rhs) { Vector v = new Vector(lhs); if (v.x == rhs.x && v.y == rhs.y && v.z == rhs.z) { return true; } else { return false; } } //重載比較運算符 public static bool operator !=(Vector lhs, Vector rhs) { return !(lhs == rhs); } } }
-------------------------------------------------------------------------主程序
Vector v1 = new Vector(1, 2, 3); Vector v2 = new Vector(1, 2, 3); Console.WriteLine(v1 == v2);//true Console.ReadKey();
標題名稱:重載運算符
標題來源:http://muchs.cn/article42/jchhhc.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供響應式網(wǎng)站、網(wǎng)站導航、營銷型網(wǎng)站建設、、域名注冊、網(wǎng)站排名
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉載內(nèi)容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)