where to declare the data that needs to be accessible to multiple objects?

倾然丶 夕夏残阳落幕 提交于 2019-12-11 17:13:02

问题


I have just started to work with multiple objects/classes and I am having a hard time figuring out how to implement the data structure properly

Assuming I have a base class

class control
{
    protected:
              char* location
              /* node** adjacency_list; This doesn't work  */

};

and two different derived classes

class carA:public control      
{

}; 

class carB:public control
{

};

and a node class.

My problem starts when I try to implement a 2D-ish structure like an array of linear linked list (graph) based on location in which the adjacency_list needs to point to the right memory space and must be available to all objects.

  • If I initialize the adjacency_list pointer to NULL at the base class constructor, with every derived class object it will be set to NULL again.

  • If I create the array in the base class constructor, it will create a new array for every derived class object.

I tried to find a way with using the copy constructor of the base class in the derived class initialization list, but I couldn't justify/visualize a way that works.

So apart from declaring it globally, what/where is a simple, sensible way to declare this pointer?

I understand this might be extremely trivial, but I just can't see it at the moment.

来源:https://stackoverflow.com/questions/48472712/where-to-declare-the-data-that-needs-to-be-accessible-to-multiple-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!