0

I have a base class,

class Msg
{
   public:

     ParseMsg()
     {
         ParseMsgData();
         ParseTrailer();
     }
     virtual void ParseMsgData() = 0;
     ParseTrailer();

};

and derived classes,

class InitiateMsg : public Msg
{
    public:
    void ParseMsgData() { ... }
};


class ReadOperationMsg  public Msg
{
   public:
    void ParseMsgData() { ... }
};


class WriteOperationMsg  public Msg
{ 
   public:

    void ParseMsgData() { ... }
};

and the scenario is below,

    void UsageFunction(string data)
    {
      Msg* msg = ParseHeader(data);
      ParseMsg
    }

   Msg* ParseHeader(string data)
   {

        Msg *msg = NULL;
           ....
         switch() 
         {

            case 1: 

                 msg = new InitiateMsg();
                 break;
            case 2:
                 msg = new ReadOperationMsg{();
                 break;
             case 3:
                 msg = new WriteOperationMsg{();
                 break;
               ....

         }

          return msg;           
    }

based on the data ParseHeader method will decide which object has to be created, So I have implemented ParseHeader function outside the class where I am using. How can I make the ParseHeader function inside the Msg class and then use it?

In C# the same is achieved by defining ParseHeader method as static with in class and use it from outside,

4

2 回答 2

4

You are in need of Abstract Factory Design pattern. It is custom made for a scenario like yours.
The inline link explains in much more in detail with an simple example than I could here.

于 2012-04-10T05:15:27.050 回答
0

好吧,在任何有用的注释之前,您忘记将它们声明为公共并且忘记在您的类定义中声明继承关系。

对于你的问题,为什么不直接将 ParseHeader 函数声明为基类 Msg 的公共成员方法。如果你这样做,我看不出任何问题。

可能存在一些依赖性问题。您需要将该方法作为声明放在 Msg 中,并在 cpp 文件中定义主体。就像是:

// in Msg.h
// all other lines are omitted
public:
  Msg* ParseHeader(string data);


// in Msg.cpp
#include "Msg.h"
#include "InitiateMsg.h"
#include "ReadOperationMsg.h"
#include "WriteOperationMsg.h"

Msg* Msg::ParseHeader(string data) {
// .....
}

另外,如果您想在拥有基指针时准确区分它是哪个类。如果我这样做,我会在基类中声明一个 emun 来记住它。就像是:

// Msg.h
class Msg{
public:
    enum type_t {
      TBase,
      TInit,
      TRead,
      TWrite
    } type;

然后在每种不同的构造方法中,给类型变量定义不同的type_t。因此,您始终可以知道指针指向哪个类,并进行动态类转换而不会错过试验。

于 2012-04-10T11:41:58.747 回答