c++函数重载代码示例
时间: 2024-06-15 21:06:47 浏览: 21
C++函数重载是指在同一个作用域内,可以定义多个同名函数,但它们的参数列表必须不同。下面是一个C++函数重载的代码示例:
```cpp
#include <iostream>
// 函数重载示例
void print(int num) {
std::cout << "整数: " << num << std::endl;
}
void print(double num) {
std::cout << "浮点数: " << num << std::endl;
}
void print(const char* str) {
std::cout << "字符串: " << str << std::endl;
}
int main() {
print(10); // 调用第一个print函数
print(3.14); // 调用第二个print函数
print("Hello"); // 调用第三个print函数
return 0;
}
```
在上面的示例中,我们定义了三个名为`print`的函数,它们的参数类型分别为`int`、`double`和`const char*`。根据传入的参数类型不同,编译器会自动选择调用对应的函数。通过函数重载,我们可以根据不同的参数类型来实现相似功能的函数。
相关问题
c++函数重载概念
函数重载是C++中的一个特性,它允许我们定义多个具有相同名称但参数类型或参数个数不同的函数。通过函数重载,我们可以使用相同的函数名来实现不同的功能,提高代码的可读性和复用性。
函数重载的概念可以通过以下示例来说明:
```cpp
#include <iostream>
// 函数重载示例
void print(int num) {
std::cout << "整数: " << num << std::endl;
}
void print(double num) {
std::cout << "浮点数: " << num << std::endl;
}
void print(const char* str) {
std::cout << "字符串: " << str << std::endl;
}
int main() {
print(10); // 调用第一个print函数,输出:整数: 10
print(3.14); // 调用第二个print函数,输出:浮点数: 3.14
print("Hello"); // 调用第三个print函数,输出:字符串: Hello
return 0;
}
```
在上面的示例中,我们定义了三个名为print的函数,它们的参数类型分别为int、double和const char*。当我们调用print函数时,编译器会根据传入的参数类型来确定调用哪个print函数。
通过函数重载,我们可以使用相同的函数名来处理不同类型的数据,使代码更加简洁和灵活。
c++重载运算符()示例代码
C++中的运算符重载是指对已有的运算符重新进行定义,赋予其不同的功能,以适应不同类型的数据。其中,圆括号()也可以被重载。下面是一个简单的示例代码:
```
#include <iostream>
using namespace std;
class Box {
public:
double getVolume() {
return length * breadth * height;
}
void setLength(double len) {
length = len;
}
void setBreadth(double bre) {
breadth = bre;
}
void setHeight(double hei) {
height = hei;
}
// 重载运算符()
double operator()(double a, double b, double c) {
length = a;
breadth = b;
height = c;
return getVolume();
}
private:
double length; // 长度
double breadth; // 宽度
double height; // 高度
};
int main() {
Box Box1; // 声明 Box1,类型为 Box
double volume;
// 使用重载的运算符() 来计算盒子的体积
volume = Box1(10.0, 5.0, 2.0);
cout << "Box1 的体积:" << volume << endl;
return 0;
}
```
在上面的示例中,我们定义了一个Box类,并在其中重载了()运算符。通过在main函数中使用重载的运算符()来计算盒子的体积,从而实现了对圆括号()的重载。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)