为了创建对象
时传递
串,必须通过值
吗?如果我有个包含串
的变量,可引用
传递它吗?
应总是对类型
和它的引用
重载构造器
吗?
对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
.