将this指针传递给构造函数

时间:2017-02-16 23:36:31

标签: oop constructor this d

我试图在D中编写一个涉及Client类的程序,该类在新客户端加入时创建新的Server对象。 我希望在创建客户端时将服务器对象传递给客户端,但是稍后当我尝试从客户端访问import std.stdio; class Server { public: int n; Client foo() //Foo creates a new client and passes this to it {return new Client(this);} } class Client { public: this(Server sv) //Constructor takes Server object {sv=sv;} Server sv; void bar() //Function bar tries to access the server's n {writeln(sv.n);} } void main() { Server s = new Server; //Create a new server object Client c = s.foo(); //Then ask for a client //c.sv=s; //!!!If I leave this line in the source then it works!!! sv.n=5; //Set it to a random value c.bar(); //Should print 5, but instead crashes w/ error -11 } 对象时,我的程序会以错误代码-11停止。我用Google搜索但没有发现任何内容。

我已在以下代码段中成功重新创建了此行为:

c.sv=s

如果我取消注释sv行,那么神奇地工作,我不明白。

那么为什么如果我在构造函数中设置writeln(sv)然后崩溃,但如果我稍后设置它然后它可以工作?

修改bar添加到null函数会打印 null ,因此会导致崩溃。但为什么它是{{1}}?

1 个答案:

答案 0 :(得分:5)

  

{SV = SV;}

这一行是错误的。它设置本地sv,而不是类实例。请尝试使用this.sv = sv;将实例成员设置为本地成员。

编辑:所以既然你从未设置过实例变量,它仍然是未初始化的 - 默认为null。