我有以下问题:
我有一个 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/