簡體   English   中英

如何在Dart中擴展Rectangle類?

[英]How to extend Rectangle class in Dart?

我想創建我的自定義矩形類,它從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;
      }  
    }

嘗試過並且工作了

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);
}

正如Günter已經表明的那樣,這是非常可能的。

更具體一點,代碼中的錯誤是對超級構造函數的調用:

super.Rectangle(left, top, width, height)應該是super(left, top, width, height)

您的語法嘗試調用命名構造函數“Rectangle”,它等同於new Rectangle.Rectangle - 該構造函數不存在。 你想調用“普通”構造函數( new Rectangle ), new Rectangle使用super調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM