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 Game::play(){
return = playerone->play();
}
答案 0 :(得分:0)
要回答有关类中的static
指针的问题:
头文件:
class Game
{
public:
Game();
~Game();
void start();
private:
static Player *playerone;
static Player *playertwo;
Matchfield gamefield;
};
源文件:
Player * Game::playerone = nullptr;
Player * Game::playertwo = nullptr;
Game::Game()
{ ; }
Game::~Game()
{
delete playerone;
delete playertwo;
}
void Game::start()
{
delete playerone;
delete playertwo;
// Example:
playerone = new Human;
playertwo = new Bot;
}
由于指针是变量,所以它们遵循相同语法,即类中的静态变量。
static
关键字表示所有Game
实例及其一个派生类的实例都有一个实例。它们全部共享相同的playerone
和playertwo
。
编辑1:方法中的静态
方法中的static
变量只能在方法内访问。 static
关键字表示变量在执行离开函数后将存在。因此,下次输入该函数时,该变量将从上次执行该函数起具有相同的值。
void AddOne()
{
static int value = 0;
std::cout << "Previous value: " << value << "\n";
++value;
std::cout << "Value after add: " << value << "\n\n";
}
int main()
{
AddOne();
AddOne();
AddOne();
AddOne();
return 0;
}
上面的代码演示了static
变量的生存期。
答案 1 :(得分:-2)
您可以将指针声明为静态的,因此在退出该方法时它不会丢失引用,但是无论何时实例化类型为Game
的对象,指针都已经被该值填充。您可以这样做:
class Game
{
public:
Game();
~Game();
void start();
private:
static Player *playerone;
static Player *playertwo;
Matchfield gamefield;
};