用c++编写,用函数重载,实现两个不同类型数据的相加,包括int型,float型,double型,一维和二维数组;编写主函数对重载函数进行测试
时间: 2024-06-13 12:08:36 浏览: 119
以下是用C++编写的函数重载实现不同类型数据相加的例子,包括int型,float型,double型,一维和二维数组:
```c++
#include<iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
float add(float a, float b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
int* add(int a[], int b[], int n) {
int* c = new int[n];
for (int i = 0; i < n; i++) {
c[i] = a[i] + b[i];
}
return c;
}
double** add(double a[][3], double b[][3], int m, int n) {
double** c = new double* [m];
for (int i = 0; i < m; i++) {
c[i] = new double[n];
for (int j = 0; j < n; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
int main() {
int a = 1, b = 2;
float c = 1.1, d = 2.2;
double e = 1.111, f = 2.222;
int arr1[] = { 1,2,3 };
int arr2[] = { 4,5,6 };
double arr3[][3] = { {1.1,2.2,3.3},{4.4,5.5,6.6} };
double arr4[][3] = { {7.7,8.8,9.9},{10.1,11.11,12.12} };
int* arr5 = add(arr1, arr2, 3);
double** arr6 = add(arr3, arr4, 2, 3);
cout << "int型相加结果:" << add(a, b) << endl;
cout << "float型相加结果:" << add(c, d) << endl;
cout << "double型相加结果:" << add(e, f) << endl;
cout << "一维数组相加结果:";
for (int i = 0; i < 3; i++) {
cout << arr5[i] << " ";
}
cout << endl;
cout << "二维数组相加结果:" << endl;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << arr6[i][j] << " ";
}
cout << endl;
}
return 0;
}
```
阅读全文