unity第二周:运算符重载

Posted on 2020-06-15 15:58  Nicela  阅读(308)  评论(0)    收藏  举报

一:

using System;
//运算符的重载:程序员自定义的运算符operator
namespace 第二周_运算符的重载
{ //复习一下静态成员,他是为各个类的实例所公有,无论多少个实例,静态成员在内存只占同一块内存。
//非静态成员创建一个实例分配一块新内存
public class shape
{
protected int len, width;


public shape(int a=0,int b=0)//小细节:这里使用默认值,下面主函数里构造不写参数就用默认值
{
len = a;
width = b;
}
public virtual int GetArea()
{
Console.WriteLine("面积:");
return (len * width);
}
public int Add(int a,int b)
{
return a + b;
}
public static shape operator+(shape a,shape b)//放在类型的类里
{
shape shape = new shape();
shape.len = a.len + b.len;
shape.width = a.width + b.width;
return shape;
}
public static shape operator-(shape a,shape b)//放在类型的类里
{
shape shape = new shape();
shape.len = a.len - b.len;
shape.width = a.width - b.width;
return shape;
}
}
class Program
{

static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}

二:

using System;

namespace 第二周_运算符的重载1
{
public class shape
{
private int len;
private int width;
private int height;
public int GetVolume()
{
return (len * width * height);
}
public void SetLen(int a)
{
len = a;
}
public void SetWidth(int b)
{
width = b;
}
public void Setheight(int c)
{
height = c;
}
public static shape operator +(shape a, shape b)//放在类型的类里
{
shape shape = new shape();
shape.len = a.len + b.len;
shape.width = a.width + b.width;
shape.height = a.height + b.height;
return shape;
}
}
class Program
{
static void Main(string[] args)
{
shape shape01 = new shape();
shape shape02 = new shape();
shape shape03 = new shape();

int Volume = 0;
shape01.SetLen(1);
shape01.SetWidth(2);
shape01.Setheight(3);

shape02.SetLen(2);
shape02.SetWidth(3);
shape02.Setheight(4);

shape03.SetLen(3);
shape03.SetWidth(4);
shape03.Setheight(5);

Volume = shape01.GetVolume();
Console.WriteLine("shape01面积:" + Volume);
Volume = shape02.GetVolume();
Console.WriteLine("shape02面积:" + Volume);
shape03 = shape01 + shape02;
Volume = shape03.GetVolume();
Console.WriteLine("shape03面积:" + Volume);
// Console.WriteLine("Hello World!");
}
}
}

博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3