结论:通过定义基类的指针并且指向派生类对象,达到调用派生类函数的目的。
前提:基类声明虚函数,派生类重写基类虚函数;
重写和重载的区别?
重写:重写父类函数,函数名,参数类型个数,返回值,必须相同;
重载:重载本身类函数,函数名必须相同,参数类型个数顺序,必须不同,返回值可以不同;
class form
{
public:
form() {}
~form() {}
virtual void fun() { cout << "form" << endl; } //虚函数
};
class circle :public form
{
public:
circle() {}
~circle() {}
void fun() { cout << "circle" << endl; } //派生类重写基类虚函数
};
class square :public form
{
public:
square() {};
~square() {};
void fun() { cout << "square" << endl; } //派生类重写基类虚函数
};
int main()
{
form *p = new circle();
p->fun();
form *p1 = new square();
p1->fun();
return 0;
}
输出:
若基类不加virtual 输出: