【问题标题】:variable is not properly set after renaming into heir重命名为继承人后未正确设置变量
【发布时间】:2019-12-29 12:26:09
【问题描述】:

我知道如何修复它(请参阅我的解决方案@bottom)但不明白为什么会发生此编译错误,因为在我看来,重命名的属性应该由 Precursor 创建到 default_create 中。为什么不是这样?

NRJ_ENTITY

inherit
    ANY
        redefine
            default_create
        end

feature {NONE} -- Initialization

    default_create
        do
            create current_day
            create current_month
            create current_year
            Precursor
        end

feature -- Access

    current_day,
    current_month,
    current_year: ENERGY_UNIT

end

NRJ_CONSUMER

inherit
    NRJ_ENTITY

end

NRJ_GENERATOR

inherit
    NRJ_ENTITY

end

NRJ_GENERATOR_CONSUMER

inherit
    NRJ_GENERATOR
        rename
            current_day as current_day_generation,
            current_month as current_month_generation,
            current_year as current_year_generation
        redefine
            default_create
        select
            current_day_generation,
            current_month_generation,
            current_year_generation
        end
    NRJ_CONSUMER
        rename
            current_day as current_day_consumption,
            current_month as current_month_consumption,
            current_year as current_year_consumption
        redefine
            default_create
        end

feature {NONE} -- Initialize

    default_create
        do
            Precursor {NRJ_GENERATOR}
            Precursor {NRJ_CONSUMER}
        end

结束

错误截图

修复 NRJ_GENERATOR_CONSUMER

default_create
    do
        create current_day_consumption
        create current_month_consumption
        create current_year_consumption
        Precursor {NRJ_CONSUMER}
        Precursor {NRJ_GENERATOR}
    end

【问题讨论】:

    标签: eiffel void-safety


    【解决方案1】:

    NRJ_GENERATOR_CONSUMER 类具有来自NRJ_ENTITY 的每个属性的两个版本。例如,current_day 有版本current_day_generationcurrent_day_consumptionNRJ_ENTITY 中的代码仅适用于current_day 的一个版本,可能已重命名。它不知道第二个版本。为了判断应该使用哪个版本的复制属性(或一般的特性),具有复制的类应该select 恰好是一个合适的版本。

    在示例中,选择的版本是current_day_generation。因此,default_create 继承自 NRJ_ENTITY 会初始化它而不是其他属性。换句话说,通过复制,

    create current_day
    

    不会自动翻译成

    create current_day_generation
    create current_day_consumption
    

    只是进入

    create current_day_generation -- The selected version.
    

    这解释了为什么您需要您所指的修复。

    另外,请注意指令Precursor {NRJ_CONSUMER}Precursor {NRJ_GENERATOR} 调用的default_create 版本与NRJ_ENTITY 中定义的完全相同,因此可以安全地删除其中一个调用。

    总结:继承的代码只处理复制功能的选定版本。

    推论:复制属性的非选定版本必须在复制它们的类中显式初始化。

    【讨论】:

    • 谢谢,最好不要同时保留Precursor 电话,以防父母之一被重新定义?
    • @Pipo 这取决于应用程序。例如,如果创建过程打开一个文件,那么调用该过程两次可能会出现问题。
    猜你喜欢
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多