[英]Acessing derived class member function using this in base class funciton, where function in overriden in derived class
[英]Using overriden function in base class constructor for derived class
我是C ++编程的新手,所以我想编写一些简单的代码来习惯语法。 目前,我故意忽略了指针和引用。
在编码期间,我正在练习继承,我想创建一个代表Hand牌的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();
}
接下来,我想创建一个名为StandHand的更具体的Hand类,该类与Hand的功能相同,但是还具有一个变量,当总数达到特定值时会发生变化。
最初,我以为我可以编写如下所示的子类,但是a。
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()方法。 如何在Hand的子类中使用add()方法时使用该子类的update()函数?
您的代码中有两个问题,首先是void update();
需要将基类中的声明为virtual
,以便编译器知道派生类可能会覆盖它并使用它。
virtual void update();
// add "=0;" if there is no base version of update()
并在派生类中编写
void update() override;
//override is unnecessary but recommended
//it verifies that you do indeed overload a method from a base class
第二个问题, 您不能在其基类的构造函数中从派生类调用方法 。 发生的情况是,调用虚拟基本方法会导致调用基本版本而不是派生版本。 想想看:尚未构造派生对象,但您已经调用了它的方法之一? 这没有任何意义。
对于代码中的入门者,没有重载函数。 派生类中的update
声明在基类中隐藏具有相同名称的函数的声明。
当成员函数add
在基类中声明时,函数update
的名称也在基类中搜索。
将功能update
声明为虚拟功能。
class Hand
{
public:
// ...
virtual void update();
};
class StandHand : public Hand
{
public:
// ///
void update() override;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.