类不包含采用0参数的构造函数

本文关键字:参数 构造函数 包含采 | 更新日期: 2024-09-25 05:51:32

由于我正在尝试创建新的myshape,但正如标题所述,出现了一个问题,我确实研究了这个问题,但我不知道如何在我的情况下解决它。这是我的班级代码

 public class Shape
    {
    private Color _color;
    private float _x, _y;
    private int _width, _height;
    private Point2D pt;
    public Shape(Color colors, float x, float y, int Width, int Height)
    {
        _color = colors;
        _x = x;
        _y = y;
        _width = Width;
        _height = Height;
        x = 0;
        y = 0;
        Width = 100;
        Height = 100;
        colors = Color.Green;
    }

以及我在主要中的表现

 public static void Main()
    {
        Shape myShape = new Shape();
        //Open the game window
        SwinGame.OpenGraphicsWindow("GameMain", 800, 600);
        SwinGame.ShowSwinGameSplashScreen();

错误为"Mygame.shapes"不包含接受0个参数的构造函数。

感谢您的帮助。

类不包含采用0参数的构造函数

Shape类只包含一个接受5个参数的构造函数:
public Shape(Color colors, float x, float y, int Width, int Height)

因此,使用适当的参数从Main显式调用它,例如:

public static void Main()
{
    Shape myShape = new Shape(Color.Green, x: 0, y: 0, Width: 10, Height: 10);

或者添加一个设置默认值的新构造函数:

public Shape()
{
    _color = Color.Green;
    _x = 0;
    _y = 0;
    _width = 100;
    _height = 100;
}

如果您不想指定参数,那么您应该在构造函数定义中提供默认值。

Optional variable-type variable-name=variable-value.

请参阅https://msdn.microsoft.com/en-us/library/dd264739.aspx.

如果没有提供默认值,则必须在创建对象时指定它们。

或者像其他人所展示的那样定义一个无参数构造函数。

创建类时,可以定义0、1或多个构造函数。每一个都必须有不同的签名。

如果您没有在类中定义构造函数,则会在场景后面定义默认构造函数。这允许您只需写(在您的示例中):就可以创建此类的实例

Shape myShape = new Shape();

如果你在类中定义了一个构造函数,一旦创建了这个类的新实例,你就必须遵循这个构造函数的签名,因为默认构造函数现在已经"消失"了。这意味着在您的情况下,您有一个接受5个参数的构造函数,因此您必须在创建Shape的新实例时调用它:

Shape myShape = new Shape( [ all the 5 parameters]);

如果您仍然想在不传递任何参数的情况下构造实例,则必须显式添加空构造函数,这是因为您定义了其他构造函数。

因此,在您的情况下,您有两个选项:

1.添加一个空构造函数(除了现有的构造函数之外):

public Shape()
{
    // here you will need to init your members with some default values        
}

2.通过调用具有5个参数的构造函数来创建实例