简体   繁体   中英

Passing class pointer in to constructor for class

Working on a collaborative project (was hoping two would be easier than one - how wrong was I...?)

Basically, what we're trying to do is a bit like this:

class first
{
    first(int * num);
};

class second
{
    second(first * frst);
    first * frt;
};

first::first(int * num)
{

}

second::second(first * frst)
{
    frt = frst;
}

There is a bit of an issue though, we can't include our Core.h file, since that contains includes to the files we're already including (there is sense somewhere there). Short version is, we're having to do something a bit more like this:

#ifndef PLAYERSTRUCTURE
#define PLAYERSTRUCTURE
// DO NOT INCLUDE CORE IN THIS FILE

class Core;

struct PlayerMem
{
    int cid;
    int y, x, z;
};

class Player
{
public:
    Player::Player(Core * coar);
    Player::Player(void);
    Player::~Player(void);
};
#endif

The Core class is declared but not defined, will this cause issues if we try to access it from within the Player class, using Core->GetSomething() etc?

Thanks

You're forwarding declaration. It's OK.

When you can use Core->GetSomething() without any compilation error then it means class Core is defined and it's not an incomplete type. So, there is no issue to use it. Just make sure you're passing a valid pointer to Core when constructing Player .

Note: In your code you're passing a pointer to a class type not a reference.

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