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别名.

发布了440 篇原创文章 · 获赞 29 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/fqbqrr/article/details/104588561
今日推荐