d如何从内部构访问外部类私变量

原文

class X {
    private int num;

    struct Y {
        // 如何访问num?
    }
}

我相信这对于嵌套/内部类是可能的,但我不知道是否对于结构体是可能的.

对构不成立,可这样绕过:

class X {
    private int num;

    struct Y {
        X outer;//显式引用.
        int fun() { return outer.num; }
    }
}

outer如何成为X的引用?自动吗?

根据用途,要return Y(this)创建构,
这样:

class X {
    private int num;

    struct Y {
        X outer;
        int fun() { return outer.num; }
    }

    Y y;
    this(){
        y = Y(this);
    }
}

void main(){
    import std.stdio : writeln;
    auto x = new X();
    x.num = 10;
    writeln(x.num);
    writeln(x.y.fun());
}
posted @ 2023-01-17 10:22  zjh6  阅读(11)  评论(0)    收藏  举报  来源