为了创建对象时传递串,必须通过值吗?如果我有个包含串的变量,可引用传递它吗?
应总是对类型和它的引用重载构造器吗?
对C变量,有个丢弃.为什么?对象不在栈上创建?
import std.stdio : writeln;
class A
{
private string str = "基";
this(ref string str)
{
writeln("引用串");
this.str = str;
}
this(string str)
{
writeln("类型串");
this.str = str;
}
this() {}
void print()
{
writeln(str);
}
}
void main()
{
auto a = new A("你好"); // 本类型串
a.print();
string text = "新串";
auto b = new A(text); // 本类型引用串
b.print();
A c;
c.print(); // 段错误,为何非`基`?
}
这里,
A c;
声明不创建类实例.你应用"new".顺便,对构不一样.
你忘了赋值"c",即:
A c = b;
按空针异常读分段错误.
赋值引用时:
ref type something
//==
myVariable = *something;//C版的类似
所以这里,不会有区别.
引用串,会变的:
void modifyString(ref string input)
{
input~= "改了";
}
string text = "串";
modifyString(text);
writeln(text); //"串改了"
几乎不应用'引用串',而应用纯'串'.
D语言比C++的引用要少得多.很少但主要在数组中用引用来改变调用者可见的长度.
不在栈上创建对象.应用'new C'创建对象.
总是同厚指针?
如果我创造的只是A c,那么它是空针吗?
是的,D的数组是胖指针.串是不变(char)数组.
是的.类是D中的引用类型.按指针实现类变量.默认值为null.










