LearnHouse

[C/C++]虛擬函式(Virtual function)與早期連結(Early Binding)、晚期連結(Late Binding)?

最近在寫模擬商店發出訊息的量測程式,使用JAVA來寫multi-thread Socket產生多條連線

JAVA可以說大學修完課後四年就沒在碰,那時也只會寫一般的數學運算並將結果印出來

所以可想而知,我是用C/C++的觀念在寫JAVA = ="

寫過C的人,應該都會覺得要站在巨人的肩膀上,才能寫出好程式

意思就是說,不透過別人現成寫好的source code來改的話

別說要寫好一個multi-thread socket,光單一條socket要建立連線就有得搞了 = ="

但這篇我主要是要講C++物件導向裡一個重要的觀念

老樣子,先隨便舉個之前的例子

class  Car
{
public:
void CarInfo()
{
printf("-------------------------\n");
printf("一般普通房車 - 新款資訊\n");
printf("-------------------------\n");
}
};

class Honda : public Car
{
public:
void CarInfo()
{
printf("-------------------------\n");
printf("Honda房車 - 新款資訊\n");
printf("-------------------------\n");
}
};

Honda繼承了Car,而且又有相同的函式CarInfo()

所以父類別的CarInfo()會被override

那麼在main裡面輸入下面的程式碼,會印出什麼結果呢?

Car *mycar;
mycar = new Honda();
mycar->CarInfo();

將將將!! 答案是印出

-------------------------
一般普通房車 - 新款資訊
-------------------------

為什麼會是這樣的結果呢??

因為編譯器預設是早期連結(Early Binding),它是一個在編譯時期就需決定的方式

那要怎麼才能使用晚期連結呢(Late Binding),它是一個在執行時期才會得知所要調用的物件

其實很簡單,只要加入virtual虛擬函式宣告即可,如下

class  Car
{
public:
virtual void CarInfo()
{
printf("-------------------------\n");
printf("一般普通房車 - 新款資訊\n");
printf("-------------------------\n");
}
};

這樣就能印出

-------------------------
Honda房車 - 新款資訊
-------------------------

這是一種「編譯時期」就需決定的方式,這是「早期繫 結」(Early binding)
posted by admin in 程式&軟體 and have Comments (5)

5 Responses to “[C/C++]虛擬函式(Virtual function)與早期連結(Early Binding)、晚期連結(Late Binding)?”

  1. At this time it appears like WordPress is the preferred blogging platform out there right now.
    (from what I've read) Is that what you are using
    on your blog?

  2. Helpful information. Lucky me I discovered your site by chance, and I'm shocked why this accident didn't happened
    in advance! I bookmarked it.

  3. Undeniably consider that that you said. Your favourite reason seemed to be
    on the net the simplest thing to bear in mind of. I say to you, I definitely get annoyed
    while other people think about worries that they
    plainly don't understand about. You controlled to hit the nail upon the highest and also defined out the entire thing with
    no need side-effects , people can take a signal. Will probably be again to get more.
    Thanks

  4. I know this if off topic but I'm looking into
    starting my own weblog and was curious what all is needed to get set up?

    I'm assuming having a blog like yours would cost a pretty penny?

    I'm not very internet savvy so I'm not 100% sure.
    Any tips or advice would be greatly appreciated.
    Many thanks

  5. Its like you read my mind! You seem to know a lot about this, like you
    wrote the book in it or something. I think that you
    could do with some pics to drive the message home a little bit,
    but instead of that, this is great blog.
    A fantastic read. I will definitely be back.

Place your comment

Please fill your data and comment below.
Name
Email
Website
Your comment