0
点赞
收藏
分享

微信扫一扫

d按传址传递串


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


举报

相关推荐

0 条评论