亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> C语言

C++ 函数重载

C++ 函数重载

在本教程中,我们将通过示例了解 C++ 中的函数重载。

在 C++ 中,如果传递的参数的数量和/或类型不同,则两个函数可以具有相同的名称。

这些具有相同名称但不同参数的函数称为重载函数。例如:

// same name different arguments
int test() { }
int test(int a) { }
float test(double a) { }
int test(int a, double b) { }

这里,4个函数都是重载函数。

请注意,所有这 4 个函数的返回类型都不相同。重载的函数可能有也可能没有不同的返回类型,但它们必须有不同的参数。例如,

// Error code
int test(int a) { }
double test(int b){ }

在这里,两个函数具有相同的名称、相同的类型和相同数量的参数。因此,编译器会抛出错误。


示例1:使用不同类型的参数重载

// Program to compute absolute value
// Works for both int and float

#include <iostream>
using namespace std;

// function with float type parameter
float absolute(float var){
    if (var < 0.0)
        var = -var;
    return var;
}

// function with int type parameter
int absolute(int var) {
     if (var < 0)
         var = -var;
    return var;
}

int main() {
    
    // call function with int type parameter
    cout << "Absolute value of -5 = " << absolute(-5) << endl;

    // call function with float type parameter
    cout << "Absolute value of 5.5 = " << absolute(5.5f) << endl;
    return 0;
}

输出

Absolute value of -5 = 5
Absolute value of 5.5 = 5.5
<图>

在这个程序中,我们重载了 absolute() 功能。根据函数调用时传递的参数类型,调用对应的函数。


示例2:使用不同数量的参数重载

#include <iostream>
using namespace std;

// function with 2 parameters
void display(int var1, double var2) {
    cout << "Integer number: " << var1;
    cout << " and double number: " << var2 << endl;
}

// function with double type single parameter
void display(double var) {
    cout << "Double number: " << var << endl;
}

// function with int type single parameter
void display(int var) {
    cout << "Integer number: " << var << endl;
}

int main() {

    int a = 5;
    double b = 5.5;

    // call function with int type parameter
    display(a);

    // call function with double type parameter
    display(b);

    // call function with 2 parameters
    display(a, b);

    return 0;
}

输出

Integer number: 5
Float number: 5.5
Integer number: 5 and double number: 5.5

这里,display() 函数用不同的参数调用了 3 次。根据传递的参数的数量和类型,相应的 display() 函数被调用。

<图>

所有这些函数的返回类型都是相同的,但函数重载不必如此。


注意: 在 C++ 中,许多标准库函数被重载。例如,sqrt() 函数可以取double , float , int, 等作为参数。这是可能的,因为 sqrt() 函数在 C++ 中被重载。


C语言

  1. C# 方法重载
  2. C# 构造函数重载
  3. C++ 运算符
  4. C++ 注释
  5. 在 C++ 编程中将数组传递给函数
  6. C++朋友函数和朋友类
  7. 将数组传递给 C 中的函数
  8. 带有示例的 C++ 运算符重载
  9. 带有程序示例的 C++ 函数
  10. C - 函数
  11. C++ 重载(运算符和函数)
  12. C++中的多态性