开发者

friend classes with pointers to each other

开发者 https://www.devze.com 2023-01-30 17:21 出处:网络
How can I create two classes that have member pointers to each other\'s class type, with full access to each other\'s data? In other words, I need two classes like this:

How can I create two classes that have member pointers to each other's class type, with full access to each other's data? In other words, I need two classes like this:

class A
{
protected:
   B *p;
};开发者_开发技巧

class B
{
protected:
   A *p;
};

I'm having trouble with it because I'm not up to par with C++ conventions, and obviously, class A can't declare a class B because B is declared later in the code.

Thanks for the help


You should use forward class declaration.

//in A.h

    class B; // forward declaration
    class A
    {
    protected:
       B *p;
       friend class B; // forward declaration
    };

//in B.h
class A; // forward declaration
class B
{
protected:
   A *p;
   friend class A; // forward declaration
};


class B;
class A {
    friend class B;
  protected:
    B *p;
};

class B {
    friend class A;
  protected:
    A *p;
};

Note that any member functions of A which actually use the members of B will have to be defined after the definition of B, for example:

class B;
class A {
    friend class B;
  protected:
    B *p;
    A *getBA();
};

class B {
    friend class A;
  protected:
    A *p;
};

A *A::getBA() { return p->p; }


you must use forward declaration like:

class B;
class A{
   ...
   friend class B;
};


class A
{
protected:
   class B *p;
};

If you want to declare friendship, you need a forward declaration:

class B;

class A
{
friend class B;
protected:
   B *p;
};


class B;
class A
{
protected:
   B *p;
   friend class B;
};

class B
{
protected:
   A *p;
   friend class A;
};


You could use a forward declaration by doing class B; above class A


simple use: class B;

class A
{
    protected:
       B *p;
       friend class B;
};

class B
{
    protected:
       A *p;
       friend class A;
};

Using class B; means a forward declaration and this basically tells the compiler: "class B exists somewhere".

0

精彩评论

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