C++虚関数の使用例

1909 ワード

一、virtualを入れない場合
include
using namespace std;
class Shape { private: public: Shape(); ~Shape(); double CalArea(); };
Shape::Shape() { cout << "Shape()"<< endl; }
Shape::~Shape() { cout << "~Shape()"<< endl; }
double Shape::CalArea() { cout << "Shape->CalArea()"<< endl; return 0; }
//circleクラスclass Circle:public Shape{private:double mR;//直径public:Circle(double r);~Circle();double CalArea();};
Circle::Circle(double r) { cout << "Circle()"<< endl; mR = r; }
Circle::~Circle() { cout << "~Circle()"<< endl; }
double Circle::CalArea() { cout << "Circle->CalArea()"<< endl; return 3.14 * mR * mR; }
//Rectクラスclass Rect:public Shape{private:double mW;double mH;
public: Rect(double w, double h); ~Rect(); double CalArea(); };
Rect::Rect(double w, double h) { cout << "Rect()"<< endl; mW = w; mH = h; }
Rect::~Rect() { cout << "~Rect()"<< endl; }
double Rect::CalArea() { cout << "Rect->CalArea()"<< endl; return mW * mH; }
int main() { Shape *s1 = new Rect(3, 6); Shape *s2 = new Circle(5);
s1->CalArea();
s2->CalArea();

delete s1;
s1 = NULL;
delete s2;
s2 = NULL;

system("pause");
return 0;

}
実行効果:Shape()Rect()Shape()Circle()Shape->CalArea()Shape->CalArea()~Shape()~Shape()任意のキーを押して続行してください.
一、virtualキーワードを加える
class Shape{...public:virtual double CalArea();//親は必ずvirtualを加えなければならない};
class Circle:public Shape{...public:...virtual double CalArea();//サブクラスのvirtualは入れなくてもいい};class Rect:public Shape{...public:...virtual double CalArea();//サブクラスのvirtualは追加しなくてもよい};
実行効果Shape()Rect()Shape()Circle()Rect->CalArea()Circle->CalArea()~Shape()~Shape()任意のキーを押して続行してください.