具有继承类和函数的抽象类写入单独的向量c++



纸牌游戏;我在用抽象类来表示握牌的"手"。"手"需要略有不同,但它们共享大部分功能。因此,有一只手和一只MasterHand,它们将继承自手,并具有额外的功能。所有东西都经过发牌的牌组。我的目标是在Hand类中公式化函数,使其能够将被调用的抽象类的实例写入handV中,而不管它是MasterHand的Hand。。我尝试过不同的方法,但都没能奏效。

class AbstractClass
{
virtual ~AbstractClass(){}        
virtual void getCard(Card::card)=0 ;
};
class Hand:public AbstractClass
{
public: 
vector<Card::card> handV;
virtual void getCard(Card::card k) override
{
writeIntoVector(k);
}
void writeIntoArray(Card::card g)
{
handV.push_back(g);
}
};
class HandMaster:public Hand
{
public: 
vector<Card::card> handV;
// now here I would like to use the functions from Hand, but make them write into HandMaster.handV rather than Hand.handV
};
class Deck
{
void passCard(AbstractBase &x)
{
x.getCard(deck.back());
}
};
int main
{
AbstractBase* k=&h;
Hand* p = static_cast<Hand*>(k);  // so I was trying to do it via casting in different convoluted ways but failed
MasterHand h2;
AbstractBase* m=&h2;
d.passCard(*k); // here I'd like the card to be passed to Hand.handV
d.passCard(*m); // here I'd like the card to be passed to MasterHand.handV
}

我添加并简化了一些代码。但我将向您介绍一些关于多态性的资源,让您开始学习。我还完全删除了AbstractClass,因为从OOP的角度来看,您有Hands和另一个MasterHand对象。

https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm

#include <vector>
#include <iostream>
//dummy class
struct Card{
int x; 
};
class Hand{
public: 
Hand(){}
std::vector<Card> handV;
virtual ~Hand(){}        
virtual void getCard(Card k) 
{
handV.push_back(k);
}
virtual void showHand() 
{
for(std::vector<Card>::const_iterator it = handV.begin(); 
it != handV.end(); 
it++) 
std::cout << it->x << " ";
}
};
class HandMaster: public Hand
{
public:
HandMaster(){} 
//add additional methods
};
class HandOther: public Hand
{
public:
HandOther(){} 
//add additional methods
};
class Deck
{
public:
std::vector<Card> deck;
Deck(){
Card c;
for(int i = 1; i <= 52; ++i){
c.x = i; 
deck.push_back(c);
}
}
void passCard(Hand *x)
{
x->getCard(deck.back());
deck.pop_back();
}
};
int main()
{
Deck d;
Hand* p = new Hand();
HandMaster *m = new HandMaster();
HandOther * o = new HandOther();
for(int i =0; i < 5; ++i){
d.passCard(p); 
d.passCard(m); 
d.passCard(o); 
}
std::cout << "nHand:";
p->showHand();
std::cout << "nHandMaster:";
m->showHand();
std::cout << "nHandOther:";
o->showHand();
std::cout << "n";
delete o;
delete p;
delete m;
}

相关内容

最新更新