具有类和结构的命名空间? [英] Namespaces with classes and structs?
问题描述
如果我有D语言的嵌套成员",那就太好了,所以我有一个聪明的想法去编码
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;
}
好的,segfault也是一个不好的例子.但是我正在学习面向对象的编程,不知道这是一件好事还是怎么做.
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.
推荐答案
本身并没有错,这里的问题是kb
仍然是null
.您需要创建一个Keyboard
对象:
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();
如果不想两次键入Keyboard
,则可以使用auto
:
If you don't want to type Keyboard
twice, you can use auto
:
auto kb = new Keyboard();
D会自动为您确定正确的类型.
And D will automatically determine the correct type for you.
将相关对象像这样分组在一起是一种相当普遍的做法,尽管通常您会想要一个比Unused
更具描述性的名称(否则,为什么要使用命名空间?).
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?).
这篇关于具有类和结构的命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!