// 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 << " ["; for (int j = 0; j < matrix.y; j++) { cout << *tmp << ", "; ++tmp; } cout << "]" << 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; }