Angular, Blockchain, Science とか

Angular, Blockchain, Science全般 の情報を主に書いていきます。

C++ virtual関数とポリモーフィズム 2

ただのサンプルb

#include <iostream>
using namespace std;

class figure{
protected:
    double x, y;
public:
    void set_dim(double i, double j){x=i;y=j;}
    virtual void show_area(){
        cout << "No area computation defined ";
        cout << "for this class " << endl;
    }
};

class triangle : public figure {
public:
    void show_area(){
        cout<<"Triangle with dimensions ";
        cout<<x<<" and base "<<y;
        cout<<" has an area of ";
        cout<<x*0.5*y<<"."<<endl;
    }
};

class rectangle : public figure {
    public:
        void show_area() {
            cout << "Rectangle eith dimensions ";
            cout << x << "x"<< y;
            cout << " has an area of ";
            cout << x*y<< endl;
        }
};

int main()
{
    figure *p;
    triangle t;
    rectangle r;
    
    p=&t;
    p->set_dim(10.0,5.0);
    p->show_area();
    p=&r;
    p->set_dim(10.0,5.0);
    p->show_area();
    
    return 0;
}