设计一个重载函数add,该函数有两个参数,可以实现两个类型相同的参数相加的操作,函
时间: 2023-12-02 17:01:16 浏览: 156
设计重载函数add的思路是,首先判断两个参数的数据类型是否相同,若相同则进行相加操作,返回结果;若不相同则给出提示信息。
函数声明如下所示:
```cpp
#include <iostream>
#include <type_traits>
template<typename T>
T add(const T& a, const T& b);
template<typename T1, typename T2>
void add(const T1& a, const T2& b);
```
具体实现如下:
```cpp
template<typename T>
T add(const T& a, const T& b) {
static_assert(std::is_same<T, T>::value, "Both parameters of add() should have the same data type.");
return a + b;
}
template<typename T1, typename T2>
void add(const T1& a, const T2& b) {
std::cout << "Error: The parameters of add() should have the same data type." << std::endl;
}
```
使用示例:
```cpp
int main() {
int a = 5, b = 3;
double x = 2.5, y = 1.5;
std::cout << "add(a, b) = " << add(a, b) << std::endl;
std::cout << "add(x, y) = " << add(x, y) << std::endl;
add(a, x);
return 0;
}
```
输出结果:
```
add(a, b) = 8
add(x, y) = 4
Error: The parameters of add() should have the same data type.
```
这个例子中,我们定义了一个重载的add函数。当两个参数的数据类型相同时,程序会调用第一个add函数进行操作;当两个参数的数据类型不同时,程序会调用第二个add函数,并给出错误提示信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![ppt](https://img-home.csdnimg.cn/images/20210720083527.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)