2017-05-06 137 views
-2

Galera,estou precisando criar umavariáveldo tipo object quepoderáinstanciar outros tipos queàherdam。C++類鑄造

傢伙我試圖創建一個對象,可以實例化的其他類型的繼承它:

#include <iostream> 
#include <cstdlib> 

class Animal { 

    public: 

     char *nome; 

     Animal (char *nome) { 
      this->nome = nome; 
     } 

}; 

class Cachorro : public Animal { 

    public: 

     bool enterraOsso; 

     Cachorro (char* nome, bool enterraOsso) : Animal(nome) { 
      this->enterraOsso = enterraOsso; 
     } 

}; 

class Passaro : public Animal { 

    public: 

     bool voar; 

     Passaro (char* nome, bool voar) : Animal(nome) { 
      this->voar = voar; 
     } 

}; 

int main() { 

    Animal *animal; 

    animal = new Cachorro("Scooby", true); 
    std::cout << animal->nome << ", " << animal->enterraOsso << std::endl; 

    animal = new Passaro("Piopio", false); 
    std::cout << animal->nome << ", " << animal->voar << std::endl; 

    return 0; 
} 

的想法是訪問子類從超還屬性。

我不知道這是一個演員還是多態,在Java中我知道這是可能的,但不能用C++來完成。

謝謝你的一切幫助。

+0

請用英文提問,或郵寄到[pt.so]代替。 – JJJ

+0

我投票結束這個問題作爲題外話,因爲它不是英文 - 這是一個**僅英文**網站 - 請尊重網站的規則! –

回答

0

可以,它是壞的設計,雖然對於一個基類來了解它的孩子:

int main() { 

    Animal *animal; 

    animal = new Cachorro("Scooby", true); 
    Cachorro * c = reinterpret_cast<Cachorro*>(animal); 
    std::cout << animal->nome << ", " << c->enterraOsso << std::endl; 


    animal = new Passaro("Piopio", false); 
    Passaro * p = reinterpret_cast<Passaro*>(animal); 
    std::cout << animal->nome << ", " << p->voar << std::endl; 

}