任务描述
本关任务:设计一个矩阵类,并实现简单的矩阵运算。
相关知识
完成本关需要具备的知识介绍请参见第一、二关卡。
编程要求
在右侧编辑器中的Begin-End
之间补充代码,设计一个矩阵类( Matrix ),并实现矩阵的简单运算,具体要求如下:
-
成员变量:这一部分学员可以自由发挥,但要求都是私有成员。
-
成员函数:
-
构造函数:
Matrix(int r,int c)
,参数 r 和 c 分别代表矩阵的行和列。 -
全部设值函数:
void Fill(int value)
,函数将矩阵内所有的元素都设置为参数 value 的值。 -
指定位置设值函数:
void Set(int r,int c,int value)
,函数将矩阵第 r 行 c 列的元素设置为 value 的值。 -
获取元素函数:
int Get(int r,int c)
函数,函数返回矩阵第 r 行 c 列的元素。 -
打印函数:
void Print()
,函数按照矩阵的形状打印出矩阵内容,每一个值后跟着一个空格。比如一个2x4
元素全为1的矩阵,打印结果为(更明显表示格式,空格均用下划线_
代替):1_1_1_1_
1_1_1_1_
-
-
普通函数:
-
Matrix operator+(Matrix &m1,Matrix &m2)
函数,重载Matrix
类的加法运算符,实现矩阵的加法运算。 -
Matrix operator-(Matrix &m1,Matrix &m2)
函数,重载Matrix
类的减法运算符,实现矩阵的减法运算。 -
Matrix operator*(Matrix &m1,Matrix &m2)
函数,重载Matrix
类的乘法运算符,实现矩阵的乘法运算。
-
测试说明
平台会对你编写的代码进行测试,比对你输出的数值与实际正确数值,只有所有数据全部计算正确才能通过测试:
注意:对于输入数据的具体测试,请查看右侧 step3/run.cpp 文件
测试输入:1 1
预期输出:
m1 + m2 :
3
m1 - m2 :
-1
m1 * m3 :
1
测试输入:2 2
预期输出:
m1 + m2 :
3 3
3 3
m1 - m2 :
-1 -1
-1 -1
m1 * m3 :
1 2
1 2
#include <iostream>
#include <string>
using namespace std;
/********* Begin *********/
class Matrix
{
//矩阵类的声明
public:
Matrix(int r,int c);
Matrix();
void Fill(int value);
void Set(int r,int c,int value);
int Get(int r,int c);
void Print();
friend Matrix operator + (Matrix& m1,Matrix &m2);
friend Matrix operator - (Matrix& m1,Matrix &m2);
friend Matrix operator * (Matrix& m1,Matrix &m2);
private:
int row, column;
int pt[10][10];
};
Matrix::Matrix()
{
}
Matrix::Matrix(int r,int c)
{
row = r;
column = c;
}
void Matrix::Print(){
for(int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
cout << this->pt[i][j] << " ";
cout << endl;
}
}
void Matrix::Fill(int value)
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
this->pt[i][j] =value;
}
}
void Matrix::Set(int r,int c,int value)
{
this->pt[r][c] =value;
}
int Matrix::Get(int r,int c)
{
return this->pt[r-1][c-1];
}
Matrix operator+(Matrix& m1,Matrix &m2)
{
Matrix temp(m1.row, m1.column);
for (int i = 0; i < m1.row; i++){
for (int j = 0; j < m1.column; j++)
temp.pt[i][j] = m1.pt[i][j] + m2.pt[i][j];
}
return temp;
}
Matrix operator-(Matrix& m1,Matrix &m2)
{
Matrix temp(m1.row, m1.column);
for (int i = 0; i < m1.row; i++){
for (int j = 0; j < m1.column; j++)
temp.pt[i][j] = m1.pt[i][j] - m2.pt[i][j];
}
return temp;
}
Matrix operator*(Matrix& m1,Matrix &m2)
{
Matrix temp(m1.row, m2.column);
for (int i = 0; i < m1.row; i++) {
for (int j = 0; j < m2.column; j++) {
long sum=0;
for (int k = 0; k < m1.column; k++) {
sum += m1.pt[i][k] * m2.pt[k][j];
}
temp.pt[i][j] = sum;
}
}
return temp;
}
/********* End *********/