比较运营商d重载类?

问题描述 投票:2回答:1

目前我正在学习d,并努力理解如何运算符重载可以为一类工作?重写opCmp有意义,工作正常的结构,但一类是需要采取右侧的对象,而不是因为我喜欢的类型。

这意味着我不能访问任何成员做一个比较。什么是在超负荷那么点?我缺少的东西吗?

oop operator-overloading d
1个回答
2
投票

当然,你可以访问你的成员:

class MyClass {
    int member;
    override int opCmp(Object other) {
        if (auto mcOther = cast(MyClass)other) {
            // other, and thus mcOther, is an instance of MyClass.
            // So we can access its members normally:
            return member < mcOther.member ? -1
                 : member > mcOther.member ?  1
                 :                            0;
        } else {
            // other is not a MyClass, so we give up:
            assert(0, "Can't compare MyClass with just anything!");
        }
    }
}

究其原因opCmp上课需要Object作为一个参数是它在Object类,从每个d类派生的引入。介绍opCmp有一个明智的选择,早在天,但较少所以现在。但是,因为我们不希望打破每一块d代码在那里使用opCmp(和opEqualstoHashtoString)带班,我们还挺坚持这样的选择。

© www.soinside.com 2019 - 2024. All rights reserved.