Namespaces with classes and structs?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 00:29:08

问题


Will be nice if I got 'nested members' in D language, so I have the inglorious idea to code


class Keyboard
{
    struct  Unused {
        string key1 = "Wake Up";
        string key2 = "Sleep";
        string key3 = "Power";
    }

    Unused unused;
}

int main()
{
    Keyboard kb;
    kb.unused.key1 = "Scroll Lock";

    return 0;
}

Okay, it's a bad example that segfault too. But I'm learning object-oriented programming and don't know if it's a good thing to do, or how to do.


回答1:


There's nothing wrong with doing that per se, the problem here is that kb is still null. You need to create a Keyboard object:

Keyboard kb = new Keyboard();

If you don't want to type Keyboard twice, you can use auto:

auto kb = new Keyboard();

And D will automatically determine the correct type for you.

It's fairly common practice to group related objects together like that into a struct, although usually you'll want a more descriptive name than Unused (otherwise, why have the namespace?).




回答2:


You can use the syntax you first suggested. Just make unused a static member. This works fine:

class Keyboard
{
    struct Unused {
         string key1 = "Wake Up";
         string key2 = "Sleep";
         string key3 = "Power";
    }

    static Unused unused;   // **This is now a static member**
}

int main()
{
    Keyboard kb;
    kb.unused.key1 = "Scroll Lock";

    return 0;
}


来源:https://stackoverflow.com/questions/3861160/namespaces-with-classes-and-structs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!