【问题标题】:How to inherit from HASH_TABLE in Eiffel?如何从 Eiffel 的 HASH_TABLE 继承?
【发布时间】:2021-01-04 14:24:02
【问题描述】:

我想创建一个 HASH_TABLE 的派生类,它实现了一些附加功能。我尝试这样实现它:

class HASH_TABLE2[G->HASHABLE]
inherit
    HASH_TABLE[G,G]
        rename
            make as make_2
        end
create
    make
feature
    make (capacity_ : INTEGER)
        do
            make_2(capacity_)
        end
end

我收到此错误:

Error: Creation instruction uses call to improper feature.

Feature name: make_2 (n: INTEGER_32)
Line: 1156
      do
->      create Result.make (n)
        if object_comparison then

我不明白为什么。如果我对继承 ARRAY[G] 做同样的事情,那么它工作正常。

【问题讨论】:

    标签: inheritance eiffel


    【解决方案1】:

    问题在于功能empty_duplicate(在错误消息中提到)使用原始创建过程make 创建了一个新的哈希表实例。但是,此功能不再是HASH_TABLE2 中的创建过程。解决方案是相应地重新定义empty_duplicate

    class HASH_TABLE2 [G -> HASHABLE]
    
    inherit
        HASH_TABLE [G, G]
            rename
                make as make_2
            redefine
                empty_duplicate
            end
    
    create
        make
    
    feature
        
        make (capacity_: INTEGER)
            do
                make_2 (capacity_)
            end
    
    feature {NONE} -- Duplication
    
        empty_duplicate (n: INTEGER_32): like Current
                -- <Precursor>
            do
                create Result.make (n)
                if object_comparison then
                    Result.compare_objects
                end
            end
    
    end
    

    请注意,虽然empty_duplicate 重新声明的主体看起来与原始的相同,但它从HASH_TABLE2 调用makeHASH_TABLE 中的make 无关,因为后者被重命名为@987654331 @。

    这给我们带来了一个问题,来自HASH_TABLEmake 是否可以保留在HASH_TABLE2 中的创建过程。除非给定的示例是简化的,否则这是可行的并且可以毫无问题地编译:

    class HASH_TABLE2 [G -> HASHABLE]
    inherit
        HASH_TABLE [G, G]
    create
        make
    end
    

    【讨论】:

    • 如果没有rename 使用Precursorredefine 会不会更优雅?
    • @U.Windl 但是,原始问题会明确指出创建过程已重命名,并且另一个过程被用作创建过程(例如,如果创建过程具有其他一些论点,未在 MWE 中显示)。
    猜你喜欢
    • 1970-01-01
    • 2018-03-10
    • 2016-06-04
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多