所以我尝试开发一个类Scoreboard和一个类Player和一个类Player2(All singleton),每个play都应该拥有一个指向这个Scoreboard的指针。当我运行我的程序时,它停止工作,我相信这是因为指针,因为它发生在我试图访问播放器指向的记分板时。所以基本的想法是: (header.h)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
class Scoreboard
{
private:
static Scoreboard *instance;
Scoreboard()
{
p1=0;
p2=0;
num=0;
board[0]="a";
};
public :
int p1;
int p2;
int num;
string board[9];
static Scoreboard *startGame()
{
if (NULL==instance)
{
instance = new Scoreboard();
}
return instance ;
};
void printScore()
{
cout<<"X "<<p1<<endl;
cout<<"O "<<p2<<endl;
}
void makeMove(string move)
{
cout<<move<<endl;
cout<<p1<<endl;
board[num]=move;
cout<<"(plays"<<move<<")"<<endl;
num++;
}
};
Scoreboard* Scoreboard::instance=NULL;
class Player
{
private :
static Player *instance;
Player(char n2,string f2,Scoreboard *sb2)
{
name=n2;
fileName=f2;
op.open(fileName.c_str());
s=sb2;
}
public:
string fileName;
char name;
string move;
ifstream op;
Scoreboard *s;
static Player *ins(char n,string f,Scoreboard *sb)
{
if (NULL==instance)
{
instance=new Player(n,f,sb);
}
return instance;
}
int makeMove()
{
cout<<name<<"'s move"<<endl;
if (!op.eof())
{
if (op.is_open())
{
cout<<"successfully opened"<<endl;
}
op>>move;
cout<<"successfully got value"<<endl;
s->makeMove(move);
return 1;
}else
{
return 0;
}
}
};
Player* Player::instance=NULL;
class Player2
{
private :
static Player2 *instance2;
Player2(char n2,string f2,Scoreboard *sb2)
{
name=n2;
fileName=f2;
op.open(fileName.c_str());
s=sb2;
}
public:
string fileName;
char name;
string move;
ifstream op;
Scoreboard *s;
static Player2 *ins(char n,string f,Scoreboard *sb)
{
if (NULL==instance2)
{
instance2=new Player2(n,f,sb);
}
return instance2;
}
int makeMove()
{
cout<<name<<"'s move"<<endl;
if (!op.eof())
{
if (op.is_open())
{
cout<<"successfully opened"<<endl;
}
op>>move;
cout<<"successfully got value"<<endl;
s->makeMove(move);
return 1;
}else
{
return 0;
}
}
};
Player2* Player2::instance2=NULL;
和.cpp将是:
#include "stdafx.h"
#include "header.h"
int main(int argc, char* argv[])
{
string store;
string temp;
string temp2;
getline(cin,store);
istringstream stm(store);
stm>>temp;
Scoreboard* si=NULL;
Player* ply1=NULL;
Player2* ply2=NULL;
if (temp=="game")
{
Scoreboard* si= Scoreboard::startGame();
cout<<si->p1<<endl;
cout<<si->p2<<endl;
cout<<si->board[0]<<endl;
}
stm>>temp;
stm>>temp2;
if (temp=="stdin"&&temp2=="stdin")
{
}else
{
ply1=Player::ins('X',temp,si);
ply2=Player2::ins('O',temp2,si);
cout<<ply1->s->p1<<endl;
-----------------------------------------------------
//This is where program stop working(I think)
-----------------------------------------------------
}
while(1)
{
ply1->makeMove();
ply2->makeMove();
}
for(int i=0;i<9;i++)
{
cout<<si->board[i]<<" ";
}
}
答案 0 :(得分:0)
我看到的一个问题是:
UISegmentedControl
if (temp=="game")
{
Scoreboard* si= Scoreboard::startGame();`
//...
}
是一个局部变量,因此在si
之外,它不再存在。上面的}
与您之前在si
中声明的si
不同:
main
因此,您在此处取消引用NULL指针,因为永远不会设置“真实”Scoreboard* si=NULL;
:
si