简体   繁体   中英

What is the correct way for me to access a public member of class A in class B when class B is a member of class A in C++?

In the below example I want to be able to access vector cList in class B in the function ShareData . How do I do that?

I have written a sample code. It fails to compile (Error message: B has no constructors). Even if it did, does the line cObj = new B(*this); introduce any circular dependency?

#include "stdafx.h"
#include <vector>

class B;

class A
{
public:
    B* cObj;
    std::vector<B*> cList;
    A()
    {
        cObj = new B(*this);
    }
};

class B
{
public:
    B(A& aObj) : aObjLocal(aObj) {};
    void ShareData(int result)
    {
        for (auto& iterator : aObjLocal.cList)
        {
            (*iterator).ShareData(result);
        }
    }
private:
    A& aObjLocal;
};


void main()
{
    A aMain;
    B bMain(aMain);
    bMain.ShareData(10);
}

Thanks in advance for sharing the knowledge.

When you are using forward declarations, you need to make sure that any usage of the forward-declared type which needs full type happens after the type becomes fully defined.

In your case, it means that your code should like following:

class B;

class A
{
public:
    B* cObj;
    std::vector<B*> cList;
    A();
};

class B {
   ...
};

inline A::A()
{
    cObj = new B(*this);
}

Also, while doing so, you certainly would want to get rid of owning B* , and instead use std::unique_ptr there.

cObj = new B(*this);
You cann use B here since it's not yet defined. Put this under the definition of B:

A::A()
{
    cObj = new B(*this);
}

and remove the inline definition.

The line

    cObj = new B(*this);

does not work in A 's constructor since the definition of B is not visible at that line. Move the implementation of A 's constructor after B has been defined.

class A { ... };

class B { ... };

inline A::A()
{
    cObj = new B(*this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM