Avoid dynamic_cast with derived classes (Cast Derived class)

前端 未结 3 1997
栀梦
栀梦 2021-01-06 23:43

I am new to C++ and came to a point, where I generate an overhead with classes. I have a QTcpSocket and read messages from it and create objects, for example MessageJoin, Me

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-07 00:42

    A better design might be to have an abstract virtual function in the Message class, called process or onReceive or similar, the sub-classes implements this function. Then in Client::messageReceived just call this function:

    message->onReceive(...);
    

    No need to for the dynamic_cast.

    I would also recommend you to look into smart pointers, such as std::unique_ptr.


    If you have private data in the Client class that is needed for the message processing functions, then there are many methods of solving that:

    • The simplest is to use a plain "getter" function in the client:

      class Client
      {
      public:
          const QList& getList() const { return listContainingUiRelatedStuff; }
          // Add non-const version if you need to modify the list
      };
      
    • If you just want add items to the list in your example, then add a function for that:

      void addStringToList(const QString& str)
          { listContainingUiRelatedStuff.push_back(str); }
      
    • Or the non-recommended variant, make Client a friend in all message classes.

    The second variant is what I recommend. For example, if you have a list of all connected clients and want to send a message to all of them, then create a function sendAll that does it.

    The big idea here is to try and minimize the coupling and dependencies between your classes. The less coupling there is, the easier it will be to modify one or the other, or add new message classes, or even completely rewrite one or the other of the involved classes without it affecting the other classes. This is why we split code into interface and implementation and data hiding.

提交回复
热议问题