简体   繁体   English

在构造函数错误中将类指针作为参数传递

[英]Passing class pointer as an argument in a constructor error

my_world.hpp我的世界.hpp

Class my_world :: public I_my_world
{  
 public:    
   my_world(hello_world* dev);  
   virtual ~my_world() {};  
   virtual int trees();  
private:  
   hello_world* const p_dev;    
}

I_my_world.hpp I_my_world.hpp

Class I_my_world  
{  
public:  
   virtual int trees() = 0;  
protected:  
   virtual ~I_my_world() {};  
}

I_hello_world.hpp I_hello_world.hpp

Class I_hello_world  
{  
public:  
   virtual void plant() = 0;  
protected:  
   virtual ~I_hello_world() {};  
}

hello_world.hpp hello_world.hpp

Class hello_world : public I_hello_world  
{ 
public:   
   hello_world() = default;  
   virtual ~hello_world() = default;  
   virtual void plant() {};  
}

my_world.cpp my_world.cpp

int my_world::trees()  
{  
   p_dev->plant();  
   return 0;  
}

my_world::my_world(hello_world* dev)  
: p_dev(nullptr)  
{  
    
}  

new_world.cpp -> inside main new_world.cpp -> 在主里面

hello_world * alpha = new hello_world();
my_world * beta = new my_world(alpha);
int b = beta ->trees();

Am I doing anything wrong here?我在这里做错了什么吗? My processor gives shell thread error.我的处理器给出了 shell 线程错误。 I just have this much code so its error is not dependent on any other code.我只有这么多代码,所以它的错误不依赖于任何其他代码。

I want to know if I am doing anything wrong code wise, if it is anything related to the processor, I can check other things.我想知道我是否在代码方面做错了什么,如果它与处理器有关,我可以检查其他事情。

This code certainly looks curious这段代码看起来很好奇

my_world::my_world(hello_world* dev) : p_dev(nullptr) 

That should be那应该是

my_world::my_world(hello_world* dev) : p_dev(dev)

Because p_dev is null, you get a crash here因为p_dev为空,你会在这里崩溃

int my_world::trees()
{
   p_dev->plant();
   return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM