将this指针传递给构造函数

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

Ada*_*ppe 5

{SV = SV;}

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

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

  • 好吧,你可以使用相同的名字,只是养成使用`this`来设置thle实例变量的习惯. (2认同)