Множественное наследование - PullRequest
0 голосов
/ 09 сентября 2011

Я прочитал множественное наследование из книги, известной как "C ++ Primer", но я получил только файл заголовка для примера, написанного в книге, что делает его немного трудным для понимания без source.cpp. Итак, мой вопрос: что такое класс Endangered и как мне определить функции-члены highlight, cuddle, onExhibit и т. Д.? 1005 *

Этот заголовочный файл также можно загрузить с здесь .

// 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 голосов
/ 09 сентября 2011

Просто используйте функции с тем же именем, типом возвращаемого значения, номером аргумента, константностью и типами аргументов (известные вместе как сигнатура функции ) в вашем классе, который вы выводите.

Например,

// 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 был такой).

где-то.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...