2014-09-03 53 views
1

我想知道這是什麼指針 Bird * object = new Cat; 它是指向一個Bird類型還是Cat類型的對象?新的類和對象的使用指針

class Bird 
{ 
public: 
    Bird() { cout << "Bird's constructor\n"; } 
    void fly() { cout << "Bird's Fly\n"; } 
    void print() { cout << "Bird's print\n"; } 
    ~Bird() { cout << "Bird's destructor\n"; } 
}; 

class Cat : public Bird 
{ 
public: 
    Cat() { cout << "Cat's constructor\n"; } 
    void fly() { cout << "cat's Fly\n"; } 
    void printCat() { cout << "Cat's print\n"; } 
    ~Cat() { cout << "Cat's destructor\n"; } 
}; 

int main() 
{ 
    Bird* object = new Cat; 
    return (0); 
} 
+0

它指向'Cat'對象內的'Bird'基類子對象。 – 2014-09-03 00:07:19

+2

這是一隻[飛貓](http://therealweeklyshow.files.wordpress.com/2012/06/flying-cat1.jpg) – quantdev 2014-09-03 00:07:39

+1

Bird * object = new Cat;很可能是最糟糕的示例代碼! – 2014-09-03 00:08:44

回答

0

如果有虛函數,可以使用以下來確定物體類型

貓* PTR = 的dynamic_cast <貓*>對象;

如果(* ptr == NULL) cout < <「object is pointing to Bird」;

+0

沒有**虛擬**成員的'dynamic_cast'不會很有幫助。這個例子中沒有多態。即使有,在這個答案中*既不*線也沒有編譯的機會,所謂 - 不準確性放大了絕對沒有描述你在做什麼,爲什麼你這樣做。 – WhozCraig 2014-09-03 01:14:03

+0

0123,括號和*由堆棧溢出修剪,用空格編輯它,這使得它顯示代碼,感謝評論 – radar 2014-09-03 05:02:08

0

奧馬爾·哈立德,

最好的方式來回答你的問題是通過簡單地運行你的代碼!

正如Igor所提到的,變量object指向的是在Cat中帶有類子對象的Bird基礎。這意味着在運行時,首先調用基類(Bird類)的構造函數,然後調用Cat類的構造函數。該對象將繼續嵌入由派生類重載的函數,但不包含派生類的添加函數。如果您運行下面的代碼:

int main() 
{ 
    Bird* object = new Cat; 
    object->fly(); 

    return (0); 
} 

您將看到以下的輸出:

Bird's constructor 
Cat's constructor 
Bird's Fly 

但是,如果您運行下面的代碼:

int main() 
{ 
    Bird* object = new Cat; 
    object->fly(); 
    object->printCat(); 
    return (0); 
} 

你會發現下面的錯誤:

 main.cpp:27:11: error: class Bird has no member named printCat 
     object->printCat(); 
    ^

如果您有任何問題,請讓我知道!

+0

首先感謝兄弟對於這個簡單的回答 ,我的理解是 2014-09-03 01:17:52

+0

嘿奧馬爾,對於遲到的回覆感到抱歉 - 不得不步出一分鐘;究竟!你懂了並完美地說出來了! :0) – 2014-09-03 04:00:25

+1

@Devrash德賽,沒問題兄弟:),thx再次爲你驚人的答案:) – 2014-09-03 04:24:06