我试图为这个编码练习运行我的代码,并且我得到了以下错误:对BumbleBee::BumbleBee()的未定义引用,对GrassHopper::GrassHopper()的未定义引用
我正在练习继承,我使用昆虫类作为基类来继承函数和方法,但是我不明白我做错了什么。任何帮助都是非常感谢的,下面是代码:
#include <iostream>
using namespace std;
// Insect class declaration
class Insect
{
protected:
int antennae;
int legs;
int eyes;
public:
// default constructor
Insect();
// getters
int getAntennae() const;
int getLegs() const;
int getEyes() const;
};
// BumbleBee class declaration
class BumbleBee : public Insect
{
public:
BumbleBee();
void sting()
{ cout << "STING!" << endl; }
};
// GrassHopper class declaration
class GrassHopper : public Insect
{
public:
GrassHopper();
void hop()
{ cout << "HOP!" << endl; }
};
// main
int main()
{
BumbleBee *bumblePtr = new BumbleBee;
GrassHopper *hopperPtr = new GrassHopper;
cout << "A bumble bee has " << bumblePtr->getLegs() << " legs and can ";
bumblePtr->sting();
cout << endl;
cout << "A grass hopper has " << hopperPtr->getLegs() << " legs and can ";
hopperPtr->hop();
delete bumblePtr;
bumblePtr = nullptr;
delete hopperPtr;
hopperPtr = nullptr;
return 0;
}
// member function definitions
Insect::Insect()
{
antennae = 2;
eyes = 2;
legs = 6;
}
int Insect::getAntennae() const
{ return antennae; }
int Insect::getLegs() const
{ return legs; }
int Insect::getEyes() const
{ return eyes; }
//Desired output
/*
A bumble bee has 6 legs and can sting!
A grass hopper has 6 legs and can hop!
*/发布于 2022-05-12 01:31:17
您已经为基类提供了构造函数定义,但没有为子类提供构造函数定义。您还需要从子类构造函数中调用基类构造函数以获得所需的输出。替换下面这样的子类构造函数:
BumbleBee() : Insect() {}大括号使其成为定义而不是声明,基类构造函数在冒号之后在初始化列表中被调用。
https://stackoverflow.com/questions/72209036
复制相似问题