// 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 << "bb]" << 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;
}
原文链接: https://www.cnblogs.com/noonjuan/p/12349756.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/193472
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!