作为属性指向另一个类的指针

Pointer to another class as a property

本文关键字:指针 另一个 属性      更新时间:2023-10-16

为什么当我尝试通过指针创建另一个类的属性时收到错误:

#ifndef SQUARE_H
#define SQUARE_H
#include <string>
//using namespace std;
    #include "Player.h"
class Square
{
public:
    Square(int); 
    void process();
protected:
    int ID;
    Player* PlayerOn;          <---
};

    #endif

和Player类是:

    #ifndef PLAYER_H
    #define PLAYER_H
    #include <string>
//using namespace std;
    #include "Square.h"
class Player
{
public:
    Player(int,int);
//  ~Player(void);
    int playDice();

private:
        int ID;
        int money;

};
#endif
我收到

:

syntax error missing ; before * (on the declaration of  Player* PlayerOn;)

和缺少类型说明符(在同一行…)

看起来像是递归包含的问题。你应该在你的square类中使用前向声明。

#ifndef SQUARE_H
#define SQUARE_H
#include <string>
//using namespace std;
class Player; //You will have to use the #include "player.h" in your .cpp
class Square
{
public:
    Square(int); 
    void process();
protected:
    int ID;
    Player* PlayerOn;          <---
};

问题是你在Player.h中包含了Square.h,所以当你得到Player* PlayerOn; Player未定义

或者在Player.h中没有#include "Square.h",这将与此代码一起工作。如果实际代码更复杂,将#include "Square.h"替换为Square class Square;

的前向声明。