(1)有两个矩阵a和b,均为2行3列。求两个矩阵之和。重载运算符“+”,使之能用于矩阵相加。如: c=a+b。 (2)编写一个友元函数来读取矩阵指定所在行列的值。 。(3)定义一个Teacher(教师)类和一个Student(学生)类,二者有一部分数据成员是相同的,例如num(号码),name(姓名),sex(性别)。编写程序,将一个Student对象(学生)转换为Teacher(教师)类,只将以上3个相同的数据成员移植过去。可以设想为:一位学生大学毕业了,留校担任教师,他原有的部分数据对现在的教师身份来说仍然是有用的,应当保留并成为其教师的数据的一部分。
时间: 2024-02-01 16:15:18 浏览: 69
(1) 代码如下:
```c++
#include<iostream>
using namespace std;
class Matrix {
private:
int m[2][3];
public:
Matrix(int a[2][3]) {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
m[i][j] = a[i][j];
}
Matrix operator+(const Matrix& n) const {
Matrix sum({0});
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
sum.m[i][j] = m[i][j] + n.m[i][j];
return sum;
}
friend int getElement(Matrix& n, int i, int j);
};
int getElement(Matrix& n, int i, int j) {
return n.m[i][j];
}
int main() {
int a[2][3] = { {1,2,3},{4,5,6} };
int b[2][3] = { {7,8,9},{10,11,12} };
Matrix m1(a), m2(b), m3({0});
m3 = m1 + m2;
cout << "The sum of two matrices is: " << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++)
cout << m3.getElement(m3, i, j) << " ";
cout << endl;
}
return 0;
}
```
(2) 友元函数的代码如下:
```c++
#include<iostream>
using namespace std;
class Matrix {
private:
int m[2][3];
public:
Matrix(int a[2][3]) {
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
m[i][j] = a[i][j];
}
Matrix operator+(const Matrix& n) const {
Matrix sum({0});
for (int i = 0; i < 2; i++)
for (int j = 0; j < 3; j++)
sum.m[i][j] = m[i][j] + n.m[i][j];
return sum;
}
friend int getElement(Matrix& n, int i, int j);
};
int getElement(Matrix& n, int i, int j) {
return n.m[i][j];
}
int main() {
int a[2][3] = { {1,2,3},{4,5,6} };
Matrix m1(a);
cout << "The element of matrix at row 1, column 2 is: " << getElement(m1, 1, 2) << endl;
return 0;
}
```
(3) 学生转教师的代码如下:
```c++
#include<iostream>
#include<string>
using namespace std;
class Student {
protected:
int num;
string name;
string sex;
public:
Student(int n, string na, string s) :num(n), name(na), sex(s) {}
void display() {
cout << "The information of student is: " << endl;
cout << num << " " << name << " " << sex << endl;
}
};
class Teacher :public Student {
private:
string course;
public:
Teacher(Student s, string c) :Student(s.num, s.name, s.sex), course(c) {}
void display() {
cout << "The information of teacher is: " << endl;
cout << num << " " << name << " " << sex << " " << course << endl;
}
};
int main() {
Student s(1001, "Tom", "Male");
Teacher t(s, "Math");
t.display();
return 0;
}
```
阅读全文