首页 文章

如何在Dart中扩展Rectangle类?

提问于
浏览
3

我想创建我的自定义矩形类,它从Rectangle类扩展 . 我错了那个类Rectangle没有声明构造函数'Rectangle',我看过Rectangle类的源代码,并且有常量构造函数 . 有可能吗?我认为可能的解决方案是使用组合而不是继承 . 谢谢你的回答 .

part of Plot;

    class PlotRectangle extends Rectangle{

      // Rectangle<int> rectangle; // as variant use composition
      String color = "red"; 

      PlotRectangle(int left, int top, int width, int height): super.Rectangle(left, top, width, height){

      }

      PlotRectangle.withColor(int left, int top, int width, int height, this.color): super.Rectangle(left, top, width, height){
        this.color = color;
      }

      void setColor(String color){
        this.color = color;
      }  
    }

2 回答

  • 2

    尝试过并且工作了

    library x;
    
    import 'dart:math';
    
    class PlotRectangle<T extends num> extends Rectangle<T> {
      PlotRectangle(T left, T top, T width, T height) : super(left, top, width, height);
    
      String color = 'red';
    
      factory PlotRectangle.fromPoints(Point<T> a, Point<T> b) {
        T left = min(a.x, b.x);
        T width = max(a.x, b.x) - left;
        T top = min(a.y, b.y);
        T height = max(a.y, b.y) - top;
        return new PlotRectangle<T>(left, top, width, height);
      }
    
      PlotRectangle.withColor(T left, T top, T width, T height, this.color) : super(left, top, width, height);
    
      @override
      String toString() => '${super.toString()}, $color';
    }
    
    void main(List<String> args) {
      var r = new PlotRectangle(17, 50, 30, 28);
      print(r);
      var rc = new PlotRectangle.withColor(17, 50, 30, 28, 'blue');
      print(rc);
    }
    
  • 2

    正如Günter已经表明的那样,这是非常可能的 .

    更具体一点,代码中的错误是对超级构造函数的调用:

    super.Rectangle(left, top, width, height) 应为 super(left, top, width, height) .

    您的语法尝试调用命名构造函数"Rectangle",它等同于 new Rectangle.Rectangle - 构造函数不存在 . 你想调用"normal"构造函数( new Rectangle ),它只使用 super 调用 .

相关问题