c语言运算符最低级(33.C运算符重载)
c语言运算符最低级(33.C运算符重载)这些二元运算符带有两个操作数,且可以被重载。 - * / %描述 - ! ~ --这些一元运算符只有一个操作数,且可以被重载。
摘要
程序员也可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。
正文
| 
     运算符  | 
     描述  | 
| 
     - ! ~ --  | 
     这些一元运算符只有一个操作数,且可以被重载。  | 
| 
     - * / %  | 
     这些二元运算符带有两个操作数,且可以被重载。  | 
| 
     == != < > <= >=  | 
     这些比较运算符可以被重载。  | 
| 
     &&  | |
| 
     = -= *= /= %=  | 
     这些赋值运算符不能被重载。  | 
| 
     = . ?: -> new is sizeof typeof  | 
     这些运算符不能被重载。  | 
创建一个Box类
internal class Box
{
    public int Length { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public int Volume()
    {
        return Length * Width * Height;
    }
    //两个箱子相加
    public static Box operator  (Box a  Box b)
    {
        Box box = new Box();
        box.Length = a.Length   b.Length;
        box.Width = a.Width   b.Width;
        box.Height = a.Height   b.Height;
        return box;
    }
    //两个箱子是否相同
    public static bool operator ==(Box a  Box b)
    {
        if(a.Length==b.Length && a.Width==b.Width && a.Height == b.Height)
        {
            return true;
        }
        return false;
    }
    //两个箱子是否不相同
    public static bool operator !=(Box a  Box b)
    {
        if (a.Length == b.Length && a.Width == b.Width && a.Height == b.Height)
        {
            return false;
        }
        return true;
    }
    public void PrintSize()
    {
        Console.WriteLine(this.Length * this.Width * this.Height);
    }
}
    
static void Main(string[] args)
{
    Box box1 = new Box();
    Box box2 = new Box();
    box1.Length = 100;
    box1.Width = 50;
    box1.Height = 50;
    box2.Length = 30;
    box2.Width = 10;
    box2.Height = 10;
    Box box3 = box1   box2;
    box3.PrintSize();
    bool isSame=box1==box2;
    Console.WriteLine(isSame);
}
    





