当前位置: 首页 > 知识库问答 >
问题:

飞镖多个构造函数

辛健
2023-03-14

真的不可能在 dart 中为一个类创建多个构造函数吗?

在我的播放器类中,如果我有这个构造函数

Player(String name, int color) {
    this._color = color;
    this._name = name;
}

然后我尝试添加这个构造函数:

Player(Player another) {
    this._color = another.getColor();
    this._name = another.getName();
}

我得到以下错误:

默认构造函数已定义。

我不是通过创建一个带有一堆非必需参数的构造函数来寻找解决方法。

有没有好办法解决这个问题?

共有3个答案

丌官嘉勋
2023-03-14

如果您已经在项目中使用了带有参数的构造函数,并且现在您发现需要一些无参数默认构造函数,则可以添加一个空构造函数。

class User{
String name;

   User({this.name}); //This you already had before
   User.empty(); //Add this later 
}
姜玉泽
2023-03-14

如果您的类使用最终参数,则接受的答案将不起作用。这样做可以:

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

  Player.fromPlayer(Player another) :
    color = another.color,
    name = another.name;
}
赵元白
2023-03-14

只能有一个未命名的构造函数,但是可以有任意数量的其他命名构造函数

class Player {
  Player(String name, int color) {
    this._color = color;
    this._name = name;
  }

  Player.fromPlayer(Player another) {
    this._color = another.getColor();
    this._name = another.getName();
  }  
}

new Player.fromPlayer(playerOne);

此构造函数可以简化

  Player(String name, int color) {
    this._color = color;
    this._name = name;
  }

  Player(this._name, this._color);

命名构造函数也可以是私有的,方法是以<code>_

class Player {
  Player._(this._name, this._color);

  Player._foo();
}

具有最终字段初始值设定项列表的构造函数是必需的:

class Player {
  final String name;
  final String color;

  Player(this.name, this.color);

  Player.fromPlayer(Player another) :
    color = another.color,
    name = another.name;
}
 类似资料:
  • 在flutter示例页面中,有一个名为“将数据发送到新屏幕”的项目。我对第65行的构造函数有一个重新保护的问题。

  • 我正在尝试修改类Circle以包含第三个构造函数,用于构造具有两个参数的Circle实例——半径的双精度和颜色的字符串。还修改主类以使用此构造函数构造Circle的实例。我对此有困难,我一直收到从未使用构造函数Circle的消息。请查看代码。

  • 我的问题是关于OOP(C)中的构造函数。当我在一个类中将默认构造函数定义为private,并且在main中将该类的一个对象初始化为default时,就会出现默认构造函数不可访问的错误。这很好。但我也在Public部分中使用默认参数构造函数,当我再次在main中初始化对象时,就会出现对函数重载的不明确调用。所以我的问题是,如果不能从main访问私有构造函数,那么编译器应该调用公共部分中的构造函数,这

  • 问题内容: 我是AP Java学生,正在为考试做练习。我遇到了这个问题,但我不明白答案: 考虑以下类别: 执行以下代码后输出是什么: 正确答案是B *。有人可以向我解释方法调用的顺序吗? 问题答案: B构造函数被调用。B构造函数的第一条隐式指令是(调用超类的默认构造函数)。因此,调用了A的构造函数。A的构造函数调用,它调用java.lang.Object构造函数,该构造函数不输出任何内容。然后被称

  • 问题内容: 这个问题已经在这里有了答案 : 如何根据参数类型重载__init__方法? (10个答案) 3年前关闭。 我有一个保存数据的容器类。创建容器时,有不同的方法来传递数据。 传递包含数据的文件 通过参数直接传递数据 不要传递数据;只是创建一个空容器 在Java中,我将创建三个构造函数。如果在Python中可行,则如下所示: 在Python中,我看到了三个明显的解决方案,但是没有一个是漂亮的

  • 请帮我从这段代码中查找错误。我还是新手,我不知道这是否正确。我确实有一个错误。这就是错误:类Person中的构造函数Person不能应用于给定类型;super();^requiredent:String,String,String找到:没有参数原因:实际和正式参数列表长度不同这是我的代码: 编辑:如果我对Person和Address类都这样做。我只能有三个ARG构造函数。如何调用one-arg构造