// matrix.cpp #include <iostream> #include <stdarg.h> #include <typeinfo> using namespace std; // a template class, to achieve any type of matrices Template < class T> class the Matrix { Private : static unsigned Short counter; // counters, calculated for each type of Matrix class how many instances unsigned Short ID; // class ID String type; // class information of type T * PTR; // points to an array matrix pointer size_t x; // number of x-axis data size_t y; // number of y-axis data size_t size; // matrix size total public : Matrix(size_t x, size_t y) { the this -> ++ ID = counter; the this -> type = the typeid (T) .name (); the this -> X = X; the this -> Y = Y; the this -> size = X * Y; the this -> PTR = new new T [size]; // matrix pointer to a one-dimensional array size sIZE } ~ the matrix () { delete []this->ptr; cout << "Matrix." << this->type << "." << this->id << " deconstructed." << endl; } // variable length parameter, input acquisition cycle 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 (lv); } // friend functions, operator overloading << Template < class the I> Friend the ostream & operator << (the ostream & OS, the Matrix <the I> & Matrix); }; // << operator overloading functions implemented Template < class the I> the ostream & operator << (the ostream & OS, the Matrix <the 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 them; } // static member variable initialization assignment Template < class T> unsigned Short the 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 *) " ! the Hello, world " , ( char *) " ! Hola, Mundo " , ( char *) " ! Hello, world " , ( char *) " ko san wa niち" ); cout << matrixCharPtr << endl; return 0; }