【问题标题】:Dispatch and inheritance (static vs. dynamic types)调度和继承(静态与动态类型)
【发布时间】:2014-04-03 23:32:24
【问题描述】:

所以在我的编译器类中,我们查看了代码

p : Point;
p <- new ColorPoint;

这里 p 被声明为一个 Point,但被分配了一个 ColorPoint 对象,而 ColorPoint 是 Point 的一个子类。

老师说p有静态类型Point,但它有动态类型ColorPoint。他说那是因为编译器在编译时不知道 p 是 ColorPoint,它只在运行时才知道。这是为什么?编译器看不到 p 被分配了一个 ColorPoint 对象吗?

【问题讨论】:

    标签: types compiler-construction


    【解决方案1】:

    是的,在这种情况下它可以,但是如果你有的话会怎样

    p : Point;
    p <- new ColorPoint;
    // some statements that operate on p
    p <- new BlackAndWhitePoint;
    // some more statements that operate on p
    

    通常,编译器无法推断出使用变量的整个上下文,因此它必须按照声明的类型进行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 2018-11-30
      • 2017-06-22
      • 1970-01-01
      • 2022-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多