Sas*_*zem 1 oop constructor d this
我正在尝试在D中编写一个程序,该程序涉及一个在新客户端加入时Server
创建新Client
对象的类.我想在创建时将服务器对象传递给客户端,但是稍后当我尝试Server
从客户端访问该对象时,我的程序将以错误代码-11停止.我用Google搜索但没有发现任何东西.
我已成功在以下代码段中重新创建此行为:
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
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释该c.sv=s
行,那么神奇地工作,我不明白.
那么为什么如果我sv
在构造函数中设置然后崩溃,但如果我稍后设置它然后它工作?
编辑:
添加writeln(sv)
到该bar
函数打印null,因此它可以导致崩溃.但为什么呢null
?
{SV = SV;}
这条线是错误的.它设置本地sv
,而不是类实例.请尝试this.sv = sv;
将实例成员设置为本地.
编辑:所以既然你从未设置实例变量,它仍然未初始化 - 默认为null.