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

时间:2018-04-07 23:01:18

标签: c++ inheritance vector virtual abstract

纸牌游戏;我正在使用抽象类来存放卡片的“手”。 “手”需要略有不同,但它们共享大部分功能。所以有一个Hand和一个MasterHand将继承Hand并具有附加功能。一切都通过卡片处理卡片。我的目标是在Hand类中以一种允许写入被调用的Abstract类实例的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
}

1 个答案:

答案 0 :(得分:1)

我添加并简化了一些代码。但是我会指出一些关于多态性的资源来帮助你入门。我也完全删除了AbstractClass,因为从OOP的角度来看,你有对象是Hands和另一个Master手对象。

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

Guess: A3
Hit A3
Guess: C4
Hit C4
Guess: A3
You've chosen that square already
Guess: B2
Hit B2
Guess: