Template Object Class

C++/CLI で template(テンプレート)機能を使って Object Class を定義します。

前田稔の超初心者のプログラム入門

プログラムの説明

  1. アルゴリズムが同じで、データの型が違うだけならテンプレート機能を使った Class がお勧めです。
    以前に説明した template(テンプレート)関数と同じように作成することが出来ます。
    template 関数の詳細は template 関数入門 を参照して下さい。
  2. 二次元座標を定義する Point Class の宣言です。
    X,Y のデータの型は、int, long, float, double など様々な型を取ることが考えられます。
    二種類の Constructor と、座標を表示する disp() 関数を宣言しています。
    /*★ template Class    前田 稔 ★*/
    #include <iostream>
    using namespace std;
    
    template <class Type> class Point
    { public:
        Type X;
        Type Y;
        Point();
        Point(Type x, Type y);
        void disp();
    };
    
  3. Point Class のメンバ関数の実装です。
    メンバ関数の頭に template Class 独特の記述があります。
    //Constructor
    template <class Type> Point<Type>::Point()
    {   X= 0;
        Y= 0;
    }
    template <class Type> Point<Type>::Point(Type x, Type y)
    {   X= x;
        Y= y;
    }
    
    //disp() 関数
    template <class Type> void Point<Type>::disp()
    {
       cout << "X=" << X << "  Y=" << Y << endl;
    }
    
  4. main() では int 型と float 型で Object Class を使ってみました。
    <実際のクラスの型>で Object Class を定義します。
    void  main()
    {
        Point<int>      *ipt;
        Point<float>    *fpt;
    
        ipt= new Point<int>(200,100);
        ipt->disp();
        fpt= new Point<float>(123.4f,56.7f);
        fpt->disp();
        delete ipt;
        delete fpt;
    }
    

超初心者のプログラム入門(C/C++)