Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I implement mutually recursive classes in C++? Something like:

/*
 * Recursion.h
 *
 */

#ifndef RECURSION_H_
#define RECURSION_H_

class Class1
{
  Class2* Class2_ptr;
public:
  void Class1_method()
  {
      //...
      (*Class2_ptr).Class2_method();
      //...
  }
};

class Class2
{
    Class1* Class1_ptr;
public:
    void Class2_method()
    {
        //...
        (*Class1_ptr).Class1_method();
        //...
    };
};


#endif /* RECURSION_H_ */
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
711 views
Welcome To Ask or Share your Answers For Others

1 Answer

  1. Forward-declare the classes (you could get away with forward-declaring only one of them, but for good form do both).
  2. Forward-declare the methods (ditto).
class Class1;
class Class2;

class Class1
{
  Class2* Class2_ptr;
public:
  void Class1_method();
};

class Class2
{
  Class1* Class1_ptr;
public:
  void Class2_method();
};

void Class1::Class1_method()
{
  //...
  (*Class2_ptr).Class2_method();
  //...
}

void Class2::Class2_method()
{
  //...
  (*Class1_ptr).Class1_method();
  //...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...