开发者

Linked list of different classes - in a maintanable way?

开发者 https://www.devze.com 2023-01-25 23:19 出处:网络
Yo people, My problem is, I have开发者_如何学JAVA to find a way to easily maintain the next situation:

Yo people,

My problem is, I have开发者_如何学JAVA to find a way to easily maintain the next situation: I have a linked list of different classes. I use void pointers, every class has "int type" as its first member.

Now when I want to call a class member function, I have to do this: - Read the int, so I know the type of the class. - I call a generic function with the type information, and also the "function" information to know which class member function to call.

So its basically a switch case in a switch case like this:

void command(void *&pointer, int type, int function)
   {
   switch (type)
      {
      case 1:
      switch (function)
         {
         case 1:
         reinterpret_cast<myClass *>(pointer)->doSomething();
         }
      }

   }

I do not even know what to do when a function, like "doSomething()" will need some arguments.

And it is a total mess anyway. I am sure there is a better way than this, but do not know what is it.

Anyone care to enlighten me?


If you find yourself writing code like "if A is of type X, then do something, and if it's of type Y, then do something else", then you are likely to be able to use polymorphism: introduce an abstract base class for those.

You would then have the list of objects of that abstract base class, and on each object you'd call a virtual method. Each class would implement it in its own way, so no case and casting would be neccessary. This is usually the best solution.

However, the only thing I can tell you without you describing your situation in more detail is: "Rethink your class design, as you're likely to have some logical mistakes there and your problem may be the consequence of those".


Virtual functions were specifically invented so you don't have to switch over types.


Use std::list, from the header <list>.

Or it may actually be that some other container may be more suitable, but you don't provide details of your problem.

Anyway, when you as a beginner feel the need to use void*, then you know that you're doing something Very Wrong™ – don't.

Cheers & hth.,


If your list of possible container element types is limited (as seems likely given the type -> value mapping you plan to use), you could implement a container of Boost Variants. This would be preferable to the brute force type -> value mapping and casting that you currently expect to need.

Without knowing more about what the objects DO, it's hard to be sure that this would work, though.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号