int main()
{
vector> arraya = {{1,3,4,5},{5,6,7,3},{8,6,8,4}};
Matrix a(3, 4);
a = arraya; //二维vector赋值给矩阵
cout << a << endl;
vector> arrayb = {{6,3,3,5},{5,2,1,3},{6,6,8,7}};
Matrix b(3, 4);
b = arrayb;
cout << b << endl;
b = b + a;
cout << b << endl;
return 0;
}
输出结果
实现
矩阵类的定义
class Matrix{
friend ostream& operator << (ostream &out, Matrix &b); //声明<<运算符重载友元
public:
Matrix(int a, int b): row(a), column(b){ //构造函数,传入矩阵行和类,并调用load初始化
load();
};
Matrix operator +(Matrix &b); //+运算符重载函数
Matrix &operator = (vector> array); //=运算符重载函数
private:
void load() //初始化数据。生成对应行列元素都是0的矩阵
{
p = new double*[row]; //让p指向 储存double指针的数组
for(int i = 0; i
+运算符重载 实现
Matrix Matrix::operator +(Matrix &b)
{
Matrix temp = *this;
for(int i=0; ip[i][t] + b.p[i][t];
}
return temp;
}
=运算符重载实现,利用传入的vector>赋值
Matrix &Matrix::operator = (vector> array)
{
for(int i=0; i
<<运算符重载实现
ostream类的拷贝构造函数和赋值函数是保护类型的,所以ostream不允许拷贝或者赋值,我们需要用两个引用来传入传出
ostream& operator << (ostream &out, Matrix &b)
{
for(int i =0; i



