我创建了一个 const 类,如下所示:
class MyClass {
const MyClass(this.x, this.y);
final double x;
final double y;
MyClass operator +(MyClass other) {
return MyClass(x + other.x, y + other.y);
}
}
现在,如果我尝试通过添加两个
const
值来创建一个新类:
const objectA = MyClass(1, 4);
const objectB = MyClass(3, 2);
const objectC = objectA + objectB;
我收到错误:
In constant expressions, operands of this operator must be of type 'num'.
如果我使用
final
它可以工作,但是:
final objectC = objectA + objectB;
我想说这是因为运算符重载方法在运行时创建了一个新类,但是
objectA
和 objectB
也是在运行时创建的,并且它们是常量。那么为什么 Dart 不能允许 objectC
成为 const
?
目前没有办法在 Dart 中定义返回除
num
之外的类的常量运算符。
因此,不能将这些运算符用作常量表达式。
更准确地说,这个错误实际上意味着“您调用的运算符不是常量。”