【问题标题】:Const constructor create non-const class objects?const构造函数创建非常量类对象?
【发布时间】:2019-05-09 15:33:03
【问题描述】:

以下代码出现错误Error: Cannot invoke a non-'const' constructor where a const expression is expected.:

class TestConst {
  final num x;
  final num y;
  TestConst(this.x, this.y);
}


void main() {

  TestConst myconst1 = const TestConst(1,2);
  TestConst myconst2 = const TestConst(1,2);

  print(identical(myconst1, myconst2));

}

虽然以下没有,但奇怪的是identical(myconst1, myconst2) 返回falseTestConst 确实只有const-constructor? :

class TestConst {
  final num x;
  final num y;
  const TestConst(this.x, this.y);
}


void main() {

  TestConst myconst1 = TestConst(1,2);
  TestConst myconst2 = TestConst(1,2);

  print(identical(myconst1, myconst2));

}

【问题讨论】:

    标签: dart


    【解决方案1】:

    const 在构造函数上意味着构造函数可以创建一个const 对象(如果调用站点选择加入并且所有构造参数也是const),而不是它只创建const 对象。

    Language Tour does mention this(但不详细):

    常量构造函数并不总是创建常量。详情见using constructors部分。

    ...

    某些类提供constant constructors。要使用常量构造函数创建编译时常量,请将 const 关键字放在构造函数名称之前:

    如果您想知道为什么使用 const 声明的构造函数在调用时仍需要显式指定 const,请参阅:Dart: Is there a disadvantage to using const constructor?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-29
      • 2018-08-15
      • 2012-12-02
      • 2019-11-20
      • 1970-01-01
      • 2018-08-14
      • 1970-01-01
      相关资源
      最近更新 更多