0
我已经从一本名为“C++ Primer”的书中读过多重继承,但是我只收到了书中示例中的头文件,这使得我在没有source.cpp的情况下理解它变得很困难。所以,我的问题是,什么是Endangered
类,我如何定义成员函数highlight
,cuddle
,onExhibit
等?多重继承
该头文件也可以从here下载。
// Multiple Inheritance.h
#include <string>
#include <iostream>
class Endangered {
public:
virtual ~Endangered();
virtual std::ostream& print(std::ostream&) const;
virtual void highlight() const;
// ...
};
class ZooAnimal;
extern std::ostream&
operator<<(std::ostream&, const ZooAnimal&);
class ZooAnimal {
public:
ZooAnimal();
ZooAnimal(std::string animal, bool exhibit,
std::string family): nm(animal),
exhibit_stat(exhibit),
fam_name(family) { }
virtual ~ZooAnimal();
virtual std::ostream& print(std::ostream&) const;
virtual int population() const;
// accessors
std::string name() const { return nm; }
std::string family_name() const { return fam_name; }
bool onExhibit() const { return exhibit_stat; }
// ...
protected:
std::string nm;
bool exhibit_stat;
std::string fam_name;
// ...
private:
};
class Bear : public ZooAnimal {
enum DanceType { two_left_feet, macarena, fandango, waltz };
public:
Bear();
Bear(std::string name, bool onExhibit=true,
std::string family = "Bear"):
ZooAnimal(name, onExhibit, family),
ival(0), dancetype(two_left_feet) { }
virtual std::ostream &print(std::ostream&) const;
virtual int toes() const;
int mumble(int);
void dance(DanceType) const;
virtual ~Bear();
private:
int ival;
DanceType dancetype;
};
class Panda : public Bear, public Endangered {
public:
Panda();
Panda(std::string name, bool onExhibit=true);
virtual ~Panda();
virtual std::ostream& print(std::ostream&) const;
void highlight();
virtual int toes();
virtual void cuddle();
// ...
};
Panda::Panda(std::string name, bool onExhibit)
: Bear(name, onExhibit, "Panda") { }
inline
std::ostream& Panda::print(std::ostream &os) const
{
Bear::print(os); // print the Bear part
Endangered::print(os); // print the Endangered part
return os;
}
class PolarBear : public Bear { /* . . . */ };
没有阅读那本书,我认为这个例子的重点并不在于挂载基类Endangered中highlight()和cuddle()的实现细节。你了解熊猫拥抱或跳舞是否真的很重要? 我评论的原因是因为你在寻找source.cpp,我认为你的方向是错误的。 –