问答题 请使用VC6或使用【答题】菜单打开 proj2下的工程proj2,其中有矩阵基类MatrixBase、矩阵类Matrix和单位阵UnitMatrix的定义,还有main函数的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。此程序的正确输出结果应为:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1
注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“// ****found*****”。
#include <iostream>
using namespace std;
//矩阵基础类,一个抽象类
class MatrixBase{
int rows, cols;
public:
MatrixBase (int rows, int cols):rows (rows), cols(cols){}
int getRows() const {return rows;} //矩阵行数
int getCols() const {return cols;} //矩阵列数
virtual double getElement (int r, int c)const = 0; //取第i个元素的值
void show() const { //分行显示矩阵中所有元素
for(int i = 0; i < rows; i++) {
cout << endl;
for (int j = 0; j < cols; j++)
// **********found**********
cout <<______<< " ";
}
}
};
//矩阵类
class Matrix: public MatrixBase{
double * val;
public:
// **********found**********
Matrix (int rows, int cols, double m[] = NULL):______{
// **********found**********
val =______;
for(int i = 0; i < rows * cols; i++)
val[i] = (m==NULL? 0.0:m[i]);
}
~Matrix() {delete []val;}
double getElement (int r, int c) const{return val[r * getCols() +c];)
};
//单位阵(主对角线元素都是1,其余元素都是0的方阵)类
class UnitMatrix: public MatrixBase {
public:
UnitMatrix (int rows): MatrixBase(rows, rows) {}
//单位阵行数列数相同
double getElement (int r, int c) const {
// **********found**********
if(______) return 1.0;
return 0.0;
}
};
int main() {
MatrixBase * m;
double d[] [5] = {{1,2, 3, 4,5}, {2,3,4,5,6}, {3,4,5,6,7}};
m = new Matrix (3, 5, (double *)d);
m -> show();
delete m;
cout << endl ;
m = new UnitMatrix (6);
m -> show();
delete m;
return 0;
}
【正确答案】
【答案解析】(1)getElement(i,j)
(2)MatrixBase(rows,cols)
(3)new double[rows*cols]
(4)r==c
答案考生文件夹 [考点] 本题考查MatrixBase类及其派生类Matrix和UnitMatrix,其中涉及构造函数、const函数、纯虚函数、动态数组和析构函数。派生类的构造函数要涉及基类的初始化,因此必须使用成员初始化列表。动态数组要先使用new语句分配空间,再赋值。
[解析] (1)主要考查考生对纯虚函数的掌握,函数功能是分行显示矩阵中所有元素。因此在这里要输出行为i、列为j的元素,使用纯虚函数getElement(i,j)实现,输出语句为cout<<getElement(i,j)<<" ";。
(2)主要考查考生对派生类的构造函数的掌握,派生类的构造函数使用成员列表初始化法,先对基类初始化。
(3)主要考查考生对动态数组的掌握,val是double型指针,要给val赋值,就要先给它分配空间,应使用new来完成。
(4)主要考查考生对成员函数的掌握,因为要输出单位矩阵,只有满足条件r==c的元素为1.0,所以填写语句if(r==c) return 1.0;。