我的代码不会链接:"undefined reference to BumbleBee::BumbleBee()"



我正试图运行我的代码为这个编码练习,我得到这个错误:未定义的引用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!
*/

您已经为基类提供了构造函数定义,但没有为子类提供构造函数定义。您还需要从子类构造函数调用基类构造函数来获得所需的输出。像这样替换子类的构造函数:

BumbleBee() : Insect() {}

大括号使其成为定义而不是声明,并且在冒号后面的初始化列表中调用基类构造函数。

最新更新