34用d编程别名

aliasalias this无关.

Stack!(Point!double) randomPoints(size_t count) {
    auto points = new Stack!(Point!double);
    // ...
}

可这样:
长名,难读,没必要每个地点都详细说明.如果改,也麻烦,到处改.

alias Points = Stack!(Point!double);

// ...

Points randomPoints(size_t count) {
    auto points = new Points;
    // ...
}
//还可以更进一步
alias PrecisePoint = Point!double;
alias Points = Stack!PrecisePoint;

语法如下:alias new_name = existing_name;
还有 消歧时很有用.为了更可读:

alias CustomerNumber = int;
alias CompanyName = string;
// ...

struct Customer {
    CustomerNumber number;
    CompanyName company;
    // ...
}
//--------
class Box {
private:

    Weight weight_;

public:

    alias Weight=double;//别名,以后更改类型也方便

    Weight weight() const @property {
        return weight_;
    }//
    // ...
}

子类会隐藏父类同名函数

class Super {
    void foo(int x) {
        // ...
    }
}

class Sub : Super {
    void foo() {
        // ...
    }
    //覆盖的话,要加个`override`,才算覆盖.
    //加上下句
    alias foo = Super.foo;//满血复活
    //或alias generalFoo = Super.foo;//类似
}

void main() {
    auto object = new Sub;
    object.foo(42);//编译错误,你找不到父类的该函数.
}

这个特征叫隐藏名称.不这样的话,有可能你都不知道你调用了哪个父类的函数.错都不知道哪错了,这是面向对象编程的特征
隐藏名称同样会对成员变量起作用:

class Super {
    int city;
}

class Sub : Super {
    string city() const @property {
        return "Kayseri";
    }//属性也可以隐藏父类名字
//加上这句
    alias cityCode = Super.city;
}

with用于简化书写.特别是对麻烦的构,赋值时.

struct S {
    int i;
    int j;
}

void main() {
    auto s = S();

    with (s) {
        i = 1;    // 即s.i
        j = 2;    // 即s.j
    }
}
    with (S()) {//还可以临时变量
        i = 1;
        j = 2;
    }//出来就没了,不知道有啥用?

后面要讲,用关键字,构建临时变量来扩展生命期
开关语句中很有用:

enum Color { red, orange }

// ...
    final switch (c) with (Color) {
//去掉,对枚举类的类名的重复引用
    case red:       //即Color.red
        // ...
    case orange:    //即Color.orange
        // ...
    }

with移除对同一对象的重复引用.alias别名.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值