C++ 模板類實現任意類型矩陣


 

// matrix.cpp
#include <iostream>
#include <stdarg.h>
#include <typeinfo>

using namespace std;

// 使用模板類,實現任意類型矩陣類
template <class T>
class Matrix
{
private:
    static unsigned short counter;        // 計數器,計算每一種類型的Matrix類有多少個實例
    unsigned short id;                    // 類的id
    string type;                        // 類的type的信息
    T *ptr;                                // 指向數組的矩陣指針
    size_t x;                            // x軸的數據數量
    size_t y;                            // y軸的數據數量
    size_t size;                        // 矩陣總大小
public:
    Matrix(size_t x, size_t y) 
    {
        this->id = ++counter;
        this->type = typeid(T).name();
        this->x = x;
        this->y = y;
        this->size = x * y;
        this->ptr = new T[size];        // 矩陣指針,指向一個size大小的一維數組 
    }
    ~Matrix() 
    {
        delete []this->ptr;
        cout << "Matrix." << this->type << "." << this->id << " deconstructed." << endl; 
    }
    // 不定長度參數,循環獲取輸入
    void SetVals(...) 
    {
        va_list vl;
        va_start(vl, NULL);

        T *tmp = this->ptr;
        for (int i = 0; i < this->size; i++)
        {
            *tmp = va_arg(vl, T);
            ++tmp;
        }

        va_end(vl);
    }
    // 友元函數,<<運算符重載
    template <class I> friend ostream& operator<<(ostream& os, Matrix<I>& matrix);
};
// <<運算符重載實現函數
template <class I> 
ostream& operator<<(ostream& os, Matrix<I>& matrix)
{
    I *tmp = matrix.ptr;
    // 打印x和y軸上的數據
    cout << "Matrix." << matrix.type << "." << matrix.id << endl;
    for (int i = 0; i < matrix.x ; i++)
    {
        cout << "\t[";
        for (int j = 0; j < matrix.y; j++)
        {
            cout << *tmp << ", ";
            ++tmp;
        }
        cout << "\b\b]" << endl;
    }

    return os;
}
// static成員變量初始化賦值
template<class T> unsigned short Matrix<T>::counter = 0;

int main()
{
    Matrix<int> matrixInt(2, 3);
    matrixInt.SetVals(1, 2, 3, 4, 5, 6);
    cout << matrixInt << endl;

    Matrix<int> matrixInt2(2, 4);
    matrixInt2.SetVals(1, 1, 2, 3, 5, 8, 13, 21);
    cout << matrixInt2 << endl; 

    Matrix<double> matrixDouble(3, 2);
    matrixDouble.SetVals(0.618, 1.718, 3.1415926, 2.132, 5.516, 6.2831852);
    cout << matrixDouble << endl;

    Matrix<char *> matrixCharPtr(2, 2);
    matrixCharPtr.SetVals((char *)"Hello, world!", (char *)"Hola, mundo!", (char *)"你好,世界!", (char *)"こんにちは");
    cout << matrixCharPtr << endl;

    return 0;
}

 


免責聲明!

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



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