简体   繁体   English

将类指针传递给类的构造函数

[英]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). 但是有一个问题,我们不能包含Core.h文件,因为该文件包含我们已经包含的文件(在某处有感觉)。 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? 核心类已声明但未定义,如果我们尝试使用Core-> GetSomething()等从Player类内部访问它,这会引起问题吗?

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. 当您可以使用Core->GetSomething()而没有任何编译错误时,则意味着定义了Core类,并且它不是不完整的类型。 So, there is no issue to use it. 因此,使用它没有问题。 Just make sure you're passing a valid pointer to Core when constructing Player . 只要确保在构造Player时将有效的指针传递给Core

Note: In your code you're passing a pointer to a class type not a reference. 注意:在您的代码中,您传递的是指向类类型而不是引用的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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