c++ - C++/类中相互依赖的循环依赖

标签 c++ circular-dependency forward-declaration circular-reference

我有以下问题:

我有一个 Pawn,它站在 Field 上。所以我有 Class Pawn 和 Class Field。我想要从 Field 访问站在其上的 Pawn,并且我想要从 Pawn 访问它所站在的 Field。

所以我有课:

class Pawn;
class Player;
class Field;
class PlayerList;

class Pawn
{
    public:
        int intID;
        Player* plrPlayer;
        Field* fldField;

        ...

 int getPosition()
{
    //gets the ID of the Field it stands on 
    return fldField->intID; //Here i get the error
}
}

class Field
{
    public:
    Pawn* pwnPawn;
    int intID;
    Field()
    {
        intID = -1;
    }
    Field(int intIDParam)
    {
        intID = intIDParam;
    }
};

g++ 说

Error: invalid use of incomplete type "class Field"
Error: Forward declaration of class Field

    main.cpp: In Elementfunktion »int Pawn::getPosition()«:
    main.cpp:42:24: Fehler: falsche Benutzung des unvollständigen Typs »class Field«
    main.cpp:10:7: Fehler: Vorwärtsdeklaration von »class Field«

除了在类外声明之外还有其他方法吗?还是我真的必须在需要之前在类外声明所有方法/成员?

我能做什么?谢谢。

编辑: 谢谢,但我现在尝试将它分成 .h 和 .cpp 文件。稍后我将为每个类使用一个 .h 和一个 .cpp 文件,但现在我只需要

标题.h

#ifndef _HEADERS_
#define _HEADERS_
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <vector>
using namespace std;

class Pawn;
class Player;
class Field;
class PlayerList;

class Pawn
{
    public:
        int intID;
        Player* plrPlayer;
        Field* fldField;

//Constructors....

int getPosition();
...
};
#endif 

实现.cpp

#ifndef _IMPLEMENTATIONS_
#define _IMPLEMENTATIONS_
#include "headers.h"
//Pawn.cpp
int Pawn::getPosition()
{
    return fldField->intID;
}

...

#endif

在 main.cpp 中我包含“implementations.cpp”

我得到了错误

In function Pawn::getPosition
multiple definition of Pawn::getPosition

我做错了什么?

最佳答案

单独的声明和实现。在单独的 cpp 文件中实现这些类。应该是这样的:

头文件:

class Player;
class Field;
class PlayerList;

class Pawn
{
    public:
        int intID;
        Player* plrPlayer;
        Field* fldField;

        ...

 int getPosition();

}

class Field
{
    public:
    Pawn* pwnPawn;
    int intID;
    Field()
    {
        intID = -1;
    }
    Field(int intIDParam)
    {
        intID = intIDParam;
    }
};

C++ 文件:

#include <header...>

int Pawn::getPosition()
{
    //gets the ID of the Field it stands on 
    return fldField->intID; //Here i get the error
}

不将多个类放在同一个翻译单元中也是一种普遍接受的做法,但这更像是一种指导,可以使代码更清晰。

关于c++ - C++/类中相互依赖的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343279/

相关文章:

c++ - C++ 中的返回表达式检查条件

c# - 我应该如何在 .NET 中安排我的项目/类以避免循环依赖

c++ - 两个单独文件中另一个类的类方法 friend

c++ - 我怎么知道是什么导致错误 : arithmetic on a pointer to an incomplete type 的不完整类型不完整

c++ - 如果使用嵌套命名空间,如何转发声明 C++ 结构?

c++ - 在内存映射文件中 boost C++ 偏移指针

c++ - 全局变量的默认存储类是什么?

c++ - 调试和预处理器指令

python - 如何处理tastypie中的循环导入

symfony - 序列化类 "App\Entity\User"的对象时检测到循环引用(配置限制: 1)