【发布时间】:2019-01-10 13:18:48
【问题描述】:
我想在方法中创建一个静态对象。该方法的类有一个指针,其类型为 Player。 Phayer 是一个抽象类。现在我想让指针指向一个继承自 Player 的对象。当 Methode 关闭时,该引用不应丢失。 指针是这样初始化的:
pragma once
include "Player.h"
include "Matchfield.h"
class Game
{
public:
Game();
~Game();
void start();
private:
Player *playerone;
Player *playertwo;
Matchfield gamefield;
};
现在我正在这样做:
Game::Game()
{
for (int i = 0; i < 2; i++) {
switch (CLI::getplayer())
{
case 0:
{
static HumanPlayer x;
playerone = &x;
}
case 1:
{
BotOne x;
playerone = &x;
}
default:
break;
}
}
}
然后另一个方法尝试从指针引用的对象调用方法。
int actMove;
int inheight;
while (true) {
actMove = playerone->play(gamefield);
inheight = gamefield.columnHeight(actMove);
... Bla Bla just boring stuff
我得到一个错误,找不到我的对象,为什么?不是静态的吗?
谢谢你的回答,我很感激!:)
为问题添加简约示例:
class Player
{
public:
Player() = default;
~Player() = default;
virtual int play(Matchfield ActField) = 0;
bool ishuman;
};
Game::Game()
{
static HumanPlayer x;
playerone = &x;
}
HumanPlayer 不是一个抽象类; 现在我想在其他地方使用指针 Playerone。 例如这里; 在 Humanplayer 中玩会返回一个 int;
int Game::play(){
return = playerone->play();
}
【问题讨论】:
-
1) 请提供minimal reproducible example。 2)“Isn't static?”
BotOne x;不是静态的,当它离开(case 1)范围时,playerone中会留下一个悬空指针,并且它的任何用法都会调用未定义的行为。 3)playertwo甚至没有被初始化,因此它的任何使用都会调用未定义的行为。 -
为什么要为playerone设置一个钓鱼指针。 HumanPlayer 是静态的。我在这里遇到了问题:actMove = playerone->play(gamefield);
-
这就是为什么我要minimal reproducible example。我不知道你的
CLI::getplayer()返回什么。如果它返回1,则playerone会留下一个悬空指针,因为BotOne x;不是静态的。 -
无论如何,您在 for 循环中创建的 HumanPlayer 和 BotOne 对象不存在于您的 for 循环上下文之外,因此您首先会遇到概念错误。
-
@BenjaminBarrois
HumanPlayerobject 确实,在switchcase 完成执行(以及循环)后仍然存在,因为它是static。BotOne不是静态的,因此,是的,它确实会在其作用域结束后被销毁。
标签: c++ pointers memory static