前言
父类中声明为虚函数,子类重写后为虚函数
代码
#include <iostream>
using namespace std;
struct Animal {
void speak() {
cout << "Animal::speak()" << endl;
}
void run() {
cout << "Animal::run()" << endl;
}
};
struct Cat :Animal {
virtual void speak() {
cout << "Cat::speak()" << endl;
}
virtual void run() {
cout << "Cat::run()" << endl;
}
};
struct WhiteCat :Cat {
virtual void speak() {
cout << "WhiteCat::speak()" << endl;
}
virtual void run() {
cout << "WhiteCat::run()" << endl;
}
};
int main()
{
Animal* cat = new WhiteCat();
cat->speak();
cat->run();
Cat* cat0 = new WhiteCat();
cat0->speak();
cat0->run();
WhiteCat* cat1 = new WhiteCat();
cat1->speak();
cat1->run();
//getchar();
return 0;
}
out为
Animal::speak()
Animal::run()
WhiteCat::speak()
WhiteCat::run()
WhiteCat::speak()
WhiteCat::run()
查看汇编代码
40: cat->speak();
00A268D5 mov ecx,dword ptr [cat]
00A268D8 call Animal::speak (0A21596h)
41: cat->run();
00A268DD mov ecx,dword ptr [cat]
00A268E0 call std::basic_ostream<char,std::char_traits<char> >::sentry::~sentry (0A2159Bh)
std::basic_ostream<char,std::char_traits<char> >::sentry::~sentry:
00A2159B jmp Animal::run (0A225A0h)
以及
50: cat1->speak();
00A269A2 mov eax,dword ptr [cat1]
00A269A5 mov edx,dword ptr [eax]
00A269A7 mov esi,esp
00A269A9 mov ecx,dword ptr [cat1]
00A269AC mov eax,dword ptr [edx]
00A269AE call eax //跳转 00A215A5
00A269B0 cmp esi,esp
00A269B2 call __RTC_CheckEsp (0A212F8h)
51: cat1->run();
00A269B7 mov eax,dword ptr [cat1]
00A269BA mov edx,dword ptr [eax]
00A269BC mov esi,esp
00A269BE mov ecx,dword ptr [cat1]
00A269C1 mov eax,dword ptr [edx+4]
00A269C4 call eax //跳转 00A215A0
00A269C6 cmp esi,esp
00A269C8 call __RTC_CheckEsp (0A212F8h)
00A215A5 jmp WhiteCat::speak (0A21AF0h)
00A215A0 jmp WhiteCat::run (0A22680h)
子类调用父类的成员函数
#include <iostream>
using namespace std;
struct Animal {
void speak() {
cout << "Animal::speak()" << endl;
}
void run() {
cout << "Animal::run()" << endl;
}
};
struct Cat :Animal {
virtual void speak() {
cout << "Cat::speak()" << endl;
}
virtual void run() {
cout << "Cat::run()" << endl;
}
};
struct WhiteCat :Cat {
void speak() {
Cat::speak();
cout << "WhiteCat::speak()" << endl;
}
void run() {
cout << "WhiteCat::run()" << endl;
}
};
int main()
{
Animal* cat = new WhiteCat();
cat->speak();
cat->run();
Cat* cat0 = new WhiteCat();
cat0->speak();
cat0->run();
WhiteCat* cat1 = new WhiteCat();
cat1->speak();
cat1->run();
//getchar();
return 0;
}
out为
Animal::speak()
Animal::run()
Cat::speak()
WhiteCat::speak()
WhiteCat::run()
Cat::speak()
WhiteCat::speak()
WhiteCat::run()