虚函数在派生类中的重写
1.1 使用虚函数关键字virtual
#include <iostream>
using namespace std;
struct Base
{
virtual void fun()
{
cout<<"Base::fun() is called"<<endl;
}
};
class Derive : public Base
{
public:
void fun()
{
cout<<"Derive::fun() is called"<<endl;
}
};
int main()
{
Derive d;
d.fun();
Base& b=d;
b.fun();
}
1.1 输出结果
Derive::fun() is called
Derive::fun() is called
2.1 纯虚函数,必须重写否则调用
#include <iostream>
using namespace std;
struct Base
{
virtual void fun() = 0;
};
class Derive : public Base
{
public:
void fun()
{
cout<<"Derive::fun() is called"<<endl;
}
};
int main()
{
Derive d;
d.fun();
Base& b=d;
b.fun();
}
2.2 输出结果
Derive::fun() is called
Derive::fun() is called