我想创建我的自定义矩形类,它是从 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);
}
关于inheritance - 如何在 Dart 中扩展 Rectangle 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21511886/