忽略很多细节:假设我有一个Card
包含函数的抽象类:
virtual int getType()=0;
由也GreenCard
有 a
virtual int getType()=0;
as well 的抽象派生而来。
然后GreenCard
由非抽象派生Follower
,Item
其中定义了纯虚:
int getType(){ return 1;}
在追随者类和
int getType(){ return 2;}
在 Item 类中。
后来我创建(并填写)GreenCard 指针列表
list<GreenCard*>* hand;
...我想循环打印手牌(取决于它们的类型):
list<GreenCard *>::iterator it;
for(it=hand->begin() ; it!=hand->end() ; ++i){
tp.getCorrectType(*it);
...
}
在这个函数中,我在第一行得到了 SegFault!
void getCorrectType(GreenCard* card)
{
/*SF here->*/ if(card->getType()==2){
...
}
}
我确信“卡”已正确创建和初始化,因为在上一行我在 gdb 中写入:p *card ...并且我可以看到它的所有字段(卡、绿卡和项目相关的字段-是的是一个“项目”)蜜蜂是正确的!
编辑:好的,然后是更多代码:
class Player{
list<GreenCard*>* fateDeck;
list<GreenCard*>* hand;
static const int START_HAND = 4;
Player(){
fateDeck = new list<GreenCard*> ();
hand = new list<GreenCard*>();
}
void initialize(){
DeckBuilder db;
*fateDeck = *(db.createFateDeck() );
db.deckShuffler(fateDeck);
initializeHand();
}
void initializeHand(){
for(int counter=0 ; counter<START_HAND ; counter++){
drawFateCard();
}
void drawFateCard(){
hand->push_front(fateDeck->front());
fateDeck->pop_front();
cout<<'\n'<<"Drawing from fate deck..."<<'\n'<<endl;
}
void Player::printHand(){
TypeConverter tp;
list<GreenCard *>::iterator it;
cout<<"You have " << hand->size()<<" fate cards in hand"<<'\n'
<<"They are the following:"<<endl;
for(it=hand->begin() ; it!=hand->end() ; ++it){
tp.getCorrectType(*it);
// printing depending on type
}
}
void startingPhase(){
printHand();
}
}
class DeckBuilder
{
private:
list<GreenCard*>* green;
public:
DeckBuilder();
list<GreenCard *>* createFateDeck();
void deckShuffler(list<GreenCard*>* green);
};
DeckBuilder :: DeckBuilder()
{
green = new list<GreenCard*>();
srand ( unsigned ( time (NULL) ) );
}
list<GreenCard *>* DeckBuilder :: createFateDeck()
{
int i;
for(i=0;i<40;i++) green->push_back(new Follower());
return green;
}
void DeckBuilder :: deckShuffler(list<GreenCard*>* green)
{
vector<GreenCard *> vect;
list<GreenCard*> ::iterator it;
for(it = green->begin();it!=green->end();it++)
vect.push_back((*it));
random_shuffle ( vect.begin(), vect.end() );
green->clear();
vector<GreenCard*>:: iterator it2;
for(it2 = vect.begin();it2!=vect.end();it2++)
green->push_back((*it2));
}
最终在 main()
Player pl();
pl.initialize();
pl.startingPhase;
和 printHand() 中的段错误;