C++???????????
???????????? ???????[ 2016/7/1 10:50:04 ] ????????.NET ??????????? ???
???????
??????????????????к????з???
????· virtual method table??VMT??
????· virtual function table(vftable)
????· virtual call table
????· dispatch table
????· vtable
??????Щ????????????????????????ó???????????dynamic dispatch??????????runtime method binding???????????????????
???????????????????C++?????????????vTable?????????
?????麯??
??????virtual????????ε???????麯????
???????vTable(???)??C++????runtime????????????????????????????virtual????????????????????vTable?????????????????????????????????????????????
?????????????????????????麯????????????vTable???????
#include <iostream>
#include <ctime>
using std::cout;
using std::endl;
struct Animal { void makeSound() { cout << "???????" << endl; } };
struct Cow : public Animal { void makeSound() { cout << "?????" << endl; } };
struct Pig : public Animal { void makeSound() { cout << "?????" << endl; } };
struct Donkey : public Animal { void makeSound() { cout << "?????" << endl; } };
int main(int argc?? const char * argv[])
{
srand((unsigned)time(0));
int count = 4;
while (count --) {
Animal *animal = nullptr;
switch (rand() % 3) {
case 0:
animal = new Cow;
break;
case 1:
animal = new Pig;
break;
case 2:
animal = new Donkey;
break;
}
animal->makeSound();
delete animal;
}
return 0;
}
???????????????????Animal?????????makeSound()?????????????????Animal??????????????????????????????????makeSound()????????????????ɡ?
???????????г????????????????????????????????????????4??Animal??makeSound()????????????£?
????????????????????Animal??makeSound()??????????Virtual???Σ??????????????makeSound()???????????????makeSound()?????????????????????Animal????????jump??makeSound()?????ε?????е??á?
????ok??????????Animal??makeSound()????麯???????£?
????struct Animal {
????virtual void makeSound()
????{
????cout << "???????" << endl;
????}
????};
???????л???????????????????????????????
????????????????????????????????£???????????????????
???????
??????????????????????????????Animal????????????????????????£?
struct Animal {
virtual void makeSound() { cout << "???????" << endl; }
virtual void walk() {}
void sleep() {}
};
struct Cow : public Animal { void makeSound() { cout << "?????" << endl; } };
struct Pig : public Animal { void makeSound() { cout << "?????" << endl; } };
struct Donkey : public Animal { void makeSound() { cout << "?????" << endl; } };
??????
???·???
??????????????????
2023/3/23 14:23:39???д?ò??????????
2023/3/22 16:17:39????????????????????Щ??
2022/6/14 16:14:27??????????????????????????
2021/10/18 15:37:44???????????????
2021/9/17 15:19:29???·???????·
2021/9/14 15:42:25?????????????
2021/5/28 17:25:47??????APP??????????
2021/5/8 17:01:11