C++中的虚函数
虚函数必须被实现,如果不希望被实现,必须在父类中声明为0;
#include<iostream> using namespace std; class Virtualbase { public: virtual void Demon() = 0; virtual void Base() = 0; // virtual void Base() { cout << "this is farther class" << endl; } }; class SubVirtual :public Virtualbase { public: void Demon() { cout << "this is SubVirtual!" << endl; } void Base() { cout << "this is subclass Base!" << endl; } }; int main() { Virtualbase* inst = new SubVirtual(); inst->Base(); inst->Demon(); char c; cin >> c; return 0; } /* 输出: this is subclass Base! this is SubVirtual! */
非虚函数
#include<iostream> using namespace std; class Virtualbase { public: virtual void Demon() = 0; void Base() { cout << "This is farther class" << endl; } // virtual void Base() = 0; // virtual void Base() { cout << "this is farther class" << endl; } }; class SubVirtual :public Virtualbase { public: void Demon() { cout << "this is SubVirtual!\n" << endl; } void Base() { cout << "this is subclass Base\n" << endl; } }; int main() { Virtualbase* inst = new SubVirtual(); inst->Base(); inst->Demon(); char c; cin >> c; return 0; } /* 输出 This is farther class this is SubVirtual! */