多重继承

时间:2011-09-09 16:11:45

标签: c++ multiple-inheritance

我从一本名为“C ++ Primer”的书中读过多次继承,但是我只收到了书中写的例子的头文件,这使我在没有source.cpp的情况下很难理解。所以,我的问题是,什么是Endangered类,我如何定义成员函数highlightcuddleonExhibit等?

此标头文件也可以从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 { /* . . . */ };

1 个答案:

答案 0 :(得分:0)

只需要在您派生的类中具有相同名称,返回类型,参数编号,常量和参数类型(统称为函数签名)的函数。

例如,

// Me.h

class Me : public Endangered, public ZooAnimal {
    // notice that these don't have virtual before them
    std::ostream& print(std::ostream&) const;
    void highlight() const;
    std::ostream& print(std::ostream&) const;
    int population() const;

    /* etc */
};

// Me.cpp

std::ostream& Me::print(std::ostream& stream) const { /* stuff */; return stream; }

void Me::highlight() const { /* stuff */ }

/* etc */

请注意,必须为每个类定义这些类的析构函数,而不是为派生类定义。所以你需要

ZooAnimal::~ZooAnimal() {
    /* stuff */
}

不是Me::~Me(如果Me有一个,你也需要它。)

的某个地方。