游戏.h
class Game {
public:
Game();
int name = 1;
}
游戏.cpp
#include "game.h"
Game::Game() : player(this),
{
...
}
实例化 Game 类时,我将此类的指针引用传递给玩家。
实例化播放器时我想获取整数名称。
但是我无法访问游戏指针,因为它是不完整的类型。
为什么我无法访问?
IGameActor.h
class Game; // Forward declaration of Game class
class IGameActor {
protected:
Game* game; // Pointer to the Game object
public:
virtual ~IGameActor() {}
IGameActor(Game* gamePtr) : game(gamePtr) {}
IGameActor() : game(nullptr) {}
virtual void update() = 0;
player.h
#include "IGameActor.h"
class Player : public IGameActor {
public:
Player(Game* game);
void update() override;
}
玩家.cpp
Player::Player(Game* game) : IGameActor(game) { ... }
void Player::update() {
std::cout << game->name;
}
./build.sh
src/entities/player.cpp: In member function ‘virtual void Player::update()’:
src/entities/player.cpp:54:22: error: invalid use of incomplete type ‘class Game’
54 | std::cout << game->name;
| ^~
In file included from include/entities/player.h:5,
from src/entities/player.cpp:1:
include/entities/IGameActor.h:7:7: note: forward declaration of ‘class Game’
7 | class Game; // Forward declaration of Game class
| ^~~~
Compilation failed.
文件结构:
├── game.cpp
├── game.h
├── include
│ ├── entities
│ │ ├── IGameActor.h
│ │ └── player.h
├── main.cpp
└── src
├── entities
│ └── player.cpp
我发现此代码有两个潜在问题:
您应该在player.cpp中包含game.h。只在player.h 中转发声明就可以了,因为您没有在那里访问它的成员。但是,在您的源文件中,您正在访问游戏的成员,因此必须将其包含在此处。
您的 game.h 看起来不完整,因为在 Game 构造函数中您引用了“player”成员,但我没有看到它为 Game 类声明。目前它只有一个成员,int name。假设它确实存在,一个潜在的问题是声明的顺序:类成员按声明的顺序初始化。因此,如果您初始化player(this)并且在其中需要访问int name,则必须确保name在player之前声明。换句话说,将此指针传递给初始值设定项列表中的成员是安全的,只要您仅尝试访问此时已初始化的成员即可。
示例:
课堂游戏 { ... 整数名称=1; 玩家玩家; }
但是没关系:
课堂游戏 { ... 玩家玩家; 整数名称=1; }
将是一个错误,因为玩家会在名称初始化之前尝试初始化