什么?在 Toit 中用作字段初始值设定项时是什么意思?

What does ? mean when used as a field initializer in Toit?

我正在用 Toit 编写代码。我已经看到一些使用 ? 来初始化 类 中的字段的情况。这是什么意思?

class Point:
  x ::= ?
  y ::= ?

在 Toit 中,您可以使用 ? 作为字段初始值设定项,以指示该字段将在 class 的构造函数中设置其值。如果没有构造函数,问题中的 Point 代码是不完整的,编译器会告诉你:

error: Field 'x' must be initialized in a constructor
  x ::= ?
  ^
error: Field 'y' must be initialized in a constructor
  y ::= ?
  ^

您必须在构造函数中为这两个字段提供一个值,系统才能为您创建 Point 实例。您可以通过直接从提供的参数设置字段的构造函数来实现此目的:

class Point:
  x ::= ?
  y ::= ?
  constructor .x .y:

或者您可以为初始化程序中的字段计算一个值并分配给它们:

import math

class Point:
  x/float ::= ?
  y/float ::= ?
  constructor r t:
    x = r * (math.cos t)
    y = r * (math.sin t)