应该怎么样修改这个代码
时间: 2024-03-12 11:02:46 浏览: 62
修改代码!!!
可以将模板类C的构造函数参数改为T类型的引用,这样就可以接受传入的int类型参数了。修改后的代码如下:
```cpp
#include <iostream>
using namespace std;
template <typename T>
class C {
public:
C(T& a, T& b, T& c, T& d, T& e, T& f, T& g, T& h, T& m) {
cc[0][0] = a; cc[0][1] = b; cc[0][2] = c;
cc[1][0] = d; cc[1][1] = e; cc[1][2] = f;
cc[2][0] = g; cc[2][1] = h; cc[2][2] = m;
}
C<T> operator+(const C<T>& c) {
C<T> result(
cc[0][0] + c.cc[0][0], cc[0][1] + c.cc[0][1], cc[0][2] + c.cc[0][2],
cc[1][0] + c.cc[1][0], cc[1][1] + c.cc[1][1], cc[1][2] + c.cc[1][2],
cc[2][0] + c.cc[2][0], cc[2][1] + c.cc[2][1], cc[2][2] + c.cc[2][2]
);
return result;
}
void get_num() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << cc[i][j] << " ";
}
cout << endl;
}
}
// 友元函数重载减法运算符
friend C<T> operator-(const C<T>& cc1, const C<T>& cc2) {
C<T> result(
cc1.cc[0][0] - cc2.cc[0][0], cc1.cc[0][1] - cc2.cc[0][1], cc1.cc[0][2] - cc2.cc[0][2],
cc1.cc[1][0] - cc2.cc[1][0], cc1.cc[1][1] - cc2.cc[1][1], cc1.cc[1][2] - cc2.cc[1][2],
cc1.cc[2][0] - cc2.cc[2][0], cc1.cc[2][1] - cc2.cc[2][1], cc1.cc[2][2] - cc2.cc[2][2]
);
return result;
}
private:
T cc[3][3];
};
int main() {
int input[3][3];
cout << "程序运行后结果:" << endl;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << "输入第二个二维数组的值 (" << i << ", " << j << "): ";
cin >> input[i][j];
}
}
int a = 13, b = 34, c = 56, d = 23, e = 13, f = 134, g = 34, h = 34, m = 32;
C<int> c_matrix(a, b, c, d, e, f, g, h, m);
C<int> cc2_matrix(input[0][0], input[0][1], input[0][2],
input[1][0], input[1][1], input[1][2],
input[2][0], input[2][1], input[2][2]);
C<int> result1 = c_matrix + cc2_matrix;
cout << "相加后矩阵的值:" << endl;
result1.get_num();
C<int> result2 = c_matrix - cc2_matrix;
cout << "相减后矩阵的值:" << endl;
result2.get_num();
return 0;
}
```
这样就可以通过编译了。
阅读全文