template 模板類定義


#include "stdafx.h"
#include "iostream"
#include <ctime>
using namespace std;



//全局常量size=4
const int size=4;

template <typename T>
class MyClass
{
public:
    MyClass(T* p)
    {
        for (int i = 0; i < size;i++)
        {
            array[i] = p[i];
        }
    }
    void print();
private:
    T array[size];
};
template <typename T>
//模板類函數定義需要加MyClass<T>
void MyClass<T>::print()
{
    for (int i = 0; i < size;i++)
    {
        cout << array[i] << '\t';
    }
}
int _tmain()
{
    int intArray[size] = { 1, 2, 3, 4 };
    //MyClass <double> obj(intArray);
    //double需要改成int,類的構造函數的參數要和模板類參數一致
    MyClass <int> obj(intArray);
    obj.print();
    cout << endl;
    return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM