【发布时间】:2020-01-16 13:16:53
【问题描述】:
我对 C++ 编程非常陌生,所以我想编写一些简单的代码来适应语法。我暂时故意忽略了指针和引用。
在编码期间,我正在练习继承,我想创建一个代表手牌的类 Hand。基类有一个名为 update() 的函数,用于在构造时初始化“total”和“notation”属性。此外,可以使用 add() 函数向手牌添加卡片,该函数将卡片添加到手牌并触发 update() 以适当地更新属性。
#include<vector>
class Hand
{
public:
std::vector<int> cards;
int total;
std::string notation; // Abbreviated notation of the object
// Constructor
Hand(std::vector<int> cards);
void update();
void add(int card);
}
Hand::Hand(std::vector<int> cards)
{
this->cards = cards;
update();
}
void Hand::update()
{
total = 0;
notation += "{ ";
for (int card: cards)
{
total += card;
notation += std::to_string(card) + " ";
}
notation += "}";
}
void Hand::add(int card)
{
cards.push_back(card);
update();
}
接下来,我想创建一个更具体的 Hand 类,称为 StandHand,它的功能与 Hand 相同,但它还有一个变量,当总数达到特定值时会发生变化。
最初我以为我可以编写如下所示的子类,但是唉。
class StandHand : public Hand
{
public:
int stand;
StandHand(std::vector<int> cards, int stand);
void update();
}
StandHand::StandHand(std::vector<int> cards, int stand) : Hand(cards)
{
this->stand = stand;
updateHand();
}
void StandHand::update()
{
Hand::update();
notation += stand <= total ? " (stand)" : "";
}
但是当我在 StandHand 对象上调用 add() 方法时,它不使用 StandHand::update() 方法,而是使用基本的 update() 方法。如何确保 add() 方法在 Hand 的子类中使用时使用该子类的 update() 函数?
【问题讨论】:
-
你的 C++ 书应该有一章关于虚拟继承。您可以在此处找到有关如何执行此操作的其他信息。
-
您需要了解
virtual的功能:virtual void update()可以解决问题。
标签: c++ function inheritance constructor virtual