#include <iostream>
using std::cout;
using std::endl;
class Shape{
public:
function1(){
cout << "This is call Shape's function1!" << endl; //这里并没有用虚函数,所以不能实现多态
}
virtual function2(){
cout << "This is call virtual function2 of Shape class!" << endl; //这里用了虚拟函数,所以可以实现多态
}
};
class Rect: public Shape{
public:
function1(){
cout << "This is call Rect's function1!" << endl; //不能实现多态
}
virtual function2(){
cout << "This is call virtual function2 of Rect class!" << endl; //实现多态
}
};
class Circle: public Shape{
public:
function1(){
cout << "This is call Circle's function1!" << endl; //不能实现多态
}
virtual function2(){
cout << "This is call virtual function2 of Circle class!" << endl; //实现多态
}
};
int main()
{
Shape *shapeptr;
Shape shape;
Rect rect;
Circle circle;
shapeptr = &shape;
shapeptr->function1(); //调用Shape类里的
shapeptr->function2(); //调用Shape类里的
cout << endl;
shapeptr = ▭
shapeptr->function1(); //调用Shape类里的,因为该函数不是虚函数,所以不能实现多态
shapeptr->function2(); //调用Rect类里的,因为该函数是虚函数,实现了多态
cout << endl;
shapeptr = &circle;
shapeptr->function1(); //调用Shape类里的,因为该函数不是虚函数,所以不能实现多态
shapeptr->function2(); //调用Rect类里的,因为该函数是虚函数,实现了多态
cout << endl;
return 0;
}
其实虚函数的作用是代替了一个switch结构,我们的基类指针可以指向派生类对象,而在这个过程中,虚函数必须是指针所指实际对象的类里的函数,就是刚才例子里我们看到的,指针是基类的,而指向派生类对象,但执行时调用的是派生类里的虚函数,而非虚汗数,则调用的仍然是积累里的函数