开发者

C++ Relating inheritance hierarchy

There is a C code, which we are trying to convert into C++ code. There were two inheritance hierarchies, which were manag开发者_如何学Ced by C through switch..case. That has been converted to use virtual functions in C++. Now at one point these two hierarchies have to get related. For example class A relates to A1, class B relates to B1 .... where A,B,C falls in hierarchy1 and A1, B1, C1 falls in hierarchy2. In C code, this is achieved by storing the tag field(or type field used in switch..case) of hierarchy 2 in A, B, C. Can someone guide me on how to achieve this C++ cleanly?

In C

enum NodeTag1
{
  A_Node
  , B_Node
  ....  
};

enum NodeTag2
{
   A1_Node
   , B1_Node
   ....
};

struct Node
{
   NodeTag1 tag1;
};

struct A
{
     NodeTag1 tag1;
     NodeTag2 tag2;
     ..other members...
};

struct B, C all look the same.

Now assume there are 10 functions(f1, f2..) which use NodeTag1 to do a switch.. case In C++

class Node {  //10 virtual functions (f1,f2 ..)};
class A : public Node { // 10 virtual function( f1, f2.. ) };
class B : public Node { // 10 virtual function( f1, f2.. ) };

Now there is a function like this, that gets called from instances of hierarchy 1.

int decide( NodeTag2 tag2 )
{
   switch(tag2)
   {
      ...
   }
}

How can i achieve this in C++?

Thanks, Gokul.


If you dont want to create objects at run time. You can use the following method. with only one time object creation. As you dont need to access members of the classes, single object will do your work;

class A
{

public:

 virtual f()
 {
  printf("A");
 }

 static A* behaveLikeA();

 static A* behaveLikeB();
};

class B : public A
{

public:

 virtual f()
 {
  printf("B");
 }
};

A* A::behaveLikeA()
{
 static A ag;
 return &ag;
}

A* A::behaveLikeB()
{
 static B bg;
 return &bg;
};


int main(int argc, char* argv[])
{

 A* b = A::behaveLikeB();
 b->f();

 b = A::behaveLikeA();
 b->f();
 return 0;
}


If by "relate to" you mean create the common method is the factory method. This is a virtual function in classes A, B and C that returns an object of A1, B1 or C1 resp.

class A  
{
  virtual A1 GetRelated() { return new A1(); };
}

class B: public A
{
  A1 GetRelated() { return new B1(); };
}

class A1;
class B1: public A1;
..

This of course assumes that classes A and A1 are parents of classes B and B1, your hierarchy may be different.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜