gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:02:43 25 4
gpt4 key购买 nike

纸牌游戏;我正在为持有卡片的“手”使用抽象类。 “手”需要略有不同,但它们共享大部分功能。所以有一个 Hand 和一个 MasterHand,它将继承 Hand 并具有附加功能。一切都通过发牌的牌组进行。我的目标是以一种允许写入被调用的抽象类实例的 handV 的方式在 Hand 类中制定函数 - 无论它是 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 对象和另一个 Master hand 对象。

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;
}

关于c++ - 具有继承类和函数的抽象类写入单独的 vector c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49712814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com