C#参数重载的输出

来源:百度知道 编辑:UC知道 时间:2024/04/28 15:15:45
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp03
{
class Program
{
static void Main(string[] args)
{

Rectangle a = new Rectangle(2,2);
Rectangle b = new Rectangle(3,3);
Console.WriteLine(a+b);

}
}
class Rectangle
{
public int x;
public int y;

public int X
{
get {return x;}
set { this.x = value; }
}
public int Y
{
get { return y; }
set { this.y = value; }
}
public static double operator +(Rectangle R1, Rectangle R2)
{
return R1.X * R1.Y + R2.X * R2.Y;
}
}
}
出现了这个这个问题错误 1 “Rectangle”方法没有采用“2”个参数的重载
错误 2 “Rectangl

Rectangle a = new Rectangle(2,2)是在实例化一个Rectangle对象
那么他调用的是Rectangle类的构造函数。
但是你自己写的Rectangle类没有自己实现构造函数,所以它只有一个无参的构造函数(所有的类在C#里面会有一个无参的构造函数)。那么你调用Rectangle a = new Rectangle()是可以编译通过的。
但是如果你希望在实例化的时候就能设置矩形的长宽的话,你需要自己在Rectangle里面自己实现一个带两个参数的构造函数:
public Rectangle(int x, int y)
{
this.x=x;
this.y=y;
}
这样在初始化这个矩形对象的时候也可以初始化它的长宽。

但是这个时候隐式的那个无参的构造函数将会破坏掉。这是后话,跟这个问题没什么关系了。

不知道我解释清楚没有。

请参见注释

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp03
{
class Program
{
static void Main(string[] args)
{
// 实例化矩形a
Rectangle a = new Rectangle(2,2);

// 实例化矩形b
Rectangle b = new Rectangle(3,3);

// 矩形a与矩形b相加(后面重载了操作符‘+’)
Console.WriteLine(a+b);

}
}

//矩形类
class Rectangle
{
// x,y分别代表长,宽
public int x;
public int y;

public Recta