#include<iostream> #include<string> using namespace std; class Box{ protected: double length,width,height; public: Box(double l=0,double w=0,double h=0):length(l),width(w),height(h){} Box(const Box &aBox){length=aBox.length;width=aBox.width;height=aBox.height;} virtual double volume(){return length*width*height;} void showVolume(){cout<<volume()<<endl;} }; class Carton:public Box{ protected: string material; public: Carton(string m="default",double l=0,double w=0,double h=0):Box(l,w,h){material=m;} Carton(const Carton &aCarton):Box(aCarton){material=aCarton.material;} ~Carton(){}// protected: double volume(){return 0.5*length*width*height;} }; void main() { Box aBox(2,3,4); Carton aCarton("cards",4,5,6); cout<<aBox.volume()<<endl; //cout<<aCarton.volume()<<endl; Box *pBox=&aBox; pBox->showVolume(); pBox=&aCarton; pBox->showVolume(); cout<<pBox->volume()<<endl; }; main函数最后一句调用了 aCarton的protected成员函数volume(),但是编译没有报错 如果将//cout<<aCarton.volume()<<endl;注释去掉,编译会报错 可见虚函数的确是动态的!!!