开发者

Forward declaration issues

Here is my is开发者_如何学运维sue.

I have 2 classes which I want to implement in 1 h file

lets call them class Foo and class Bar. My issue is that Bar has functions which have a return value of Foo and Foo has functions with a return value of Bar.

Therefore, how do I properly forward declare these so they can play nice with each other.

Thanks


class Foo;

class Bar{
public:
  Foo * getMyFoo();
private:
  Foo * mMyFoo;
};

class Foo{
public:
  void setMyBar(Bar *);
private:
  Bar * mTheBar;
};


It's fairly easy..

  class A; // yay, forward declared A

  class B {
    private:
      A* fPtrA;
    public:
      void mymethod(const& A) const;
  };

And a more comprehensive guide: http://www.eventhelix.com/RealtimeMantra/HeaderFileIncludePatterns.htm

Which also shows how to handle cyclical dependency:

/* ====== x.h ====== */
// Forward declaration of Y for cyclic dependency
class Y;

class X 
{
    Y *m_y;
    ...
};

/* ====== y.h ====== */
// Forward declaration of X for cyclic dependency
class X;

class Y 
{
    X *m_x;
    ...
};


You can't return by value in this situation. You'll have to pass into the function by reference or pointer, and populate that value.

   void stuff(Foo *output)
   {
      //change output;
   }

Or you can return a reference or pointer:

   Foo * stuff()
   {
      return &my_foo;
   }


Yes you can do what you asked returning by value in both classes

Header

class Foo;

class Bar{
public:
  Foo getMyFoo();
};

class Foo{
public:
  Bar getMyBar();
};

Body

Foo Bar::getMyFoo(){
  return Foo();
}

Bar Foo::getMyBar(){
  return Bar();
}

However, as other have indicated you cannot hold member variable of the other type in each class (you could do it 1 way only) at which point you start to look at pointers and probably shared_ptr and weak_ptr to maintain the relationships and then why would you want to return by value.


you can also declare a type within the other type - considering their co-dependence, it is often a good idea.

you can defer instantiation of one interface by using a template.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜