2015-04-23 41 views
-7
#include <iostream> 
using namespace std; 
class animal 
{ 

    public: 
    void breathe() 
    { 
    cout << "breathe!" << endl; 
    } 

    int height; 
}; 
class fish : public animal 
{ 
    public: 
    void breathe() 
    { 
    cout << "fish breathe!" << endl; 
    } 
    int weight; 
}; 
int main() 
{ 
    animal *p_animal = new animal(); 
    fish *p_fish = (fish *)p_animal; 

    p_fish->breathe(); 
    p_fish->weight = 2; 
    cout << p_fish->weight; //I new a animal instance,but why does it has weight property? 

    int temp; 
    cin >> temp; 
} 
+0

編譯器不會阻止你自己拍攝。你走出去的方式來做到這一點,代碼現在是越野車。 – chris

+0

你正在使用你不應該的內存。您的代碼受未定義的行爲影響。 –

+0

它沒有「重量」屬性,你只是假裝它。假裝可以讓你快樂一段時間,直到現實提醒你,世界不是那樣的。然後你學會不要對編譯器說謊。 – molbdnilo

回答

0

對你的代碼的一些意見。

在這個例子中,你可能需要虛擬功能。看到這個修改你的代碼有一些意見:

#include <iostream> 

class Animal 
{ 
    public: 
    virtual ~Animal() {} // Always define virtual destructor in this case 
    virtual void breathe() const // This fonction doesn't modify the object 
    {        // then, add 'const' at the end 
     std::cout << "breathe!" << std::endl; 
    } 
    unsigned int height; // An animal can't have a negative height ;-) 
         // then, use an unsigned type. 
}; 

class Fish : public Animal 
{ 
    public: 
    virtual ~Fish() {} 
    virtual void breathe() const 
    { 
     std::cout << "fish breathe!" << std::endl; 
    } 
    unsigned int weight; 
}; 

int main() 
{ 
    Animal* p_animal = new Animal; // Don't put() for empty constructor 
    Animal* p_fish = new Fish; 

    p_animal->breathe(); // this prints "breathe!" 
    p_fish->breathe(); // this prints "fish breathe!" even if the pointer is 
         // an pointer to Animal. It's the behaviour of virtual 
         // functions : when the code is executed, the real type 
         // is checked and the corresponding function is called. 

    p_fish->height = 10; // This works 
    // p_fish->weight = 5; // This doesn't compile, it's an pointer to Animal 

    Fish* p_real_fish = dynamic_cast<Fish*>(p_fish); 
    p_real_fish->height = 10; // This works 
    p_real_fish->weight = 5; // This works too 

    delete p_animal; // Don't forget to release the memory ! 
    delete p_fish; 
} 

我希望這可以幫助你。

1

正如各種評論者指出的那樣,你在欺騙編譯器來讓你這樣做。

重點線是

fish *p_fish = (fish *)p_animal; 

這條線基本上強制編譯器接受無論 p_animal指着,它現在指向一條魚。

如果您可以訪問那裏的屬性,那麼它基本上是機會的,而不同的編譯器可能會給你不同的結果。

如果你寫了

fish *p_fish = p_animal; 

然後編譯器會抱怨。

相關問題