C++ 函数调用

1、函数参数默认值

函数参数赋默认值时要从后往前赋值,不能后面的没有赋默认值而后面的赋了默认值,可以前面的没赋默认值,后面的赋默认值。

#include<stdlib.h>
#include<iostream>
using namespace std;

void fun(int i = 30,int j = 20,int k = 10);

int main(void)
{
    fun();
    fun(100);
    fun(100,200);
    fun(100,200,300);

    system("pause");
    return 0;
}

void fun(int i,int j,int k) // 此处可以不用写默认值,写上默认值有的编译器可能会报错。
{
    cout << i << "," << j<< "," << k<< endl;
}

运行结果:

C++ 函数调用

2、函数重载

默认是在同一个命名空间下的

编译器选择与参数适合的函数进行编译

#include<stdlib.h>
#include<iostream>
using namespace std;

void fun(int i = 30,int j = 20,int k = 10);
void fun(double i,double j);

int main(void)
{
    fun(1.11,2.22);
    fun(100,200);

    system("pause");
    return 0;
}

void fun(int i,int j,int k) // 此处可以不用写默认值,写上默认值有的编译器可能会报错。
{
    cout << i << "," << j<< "," << k<< endl;
}

void fun(double i,double j)
{
    cout << i << "," << j << endl;
}

运行结果:

C++ 函数调用

3、内联函数

内联函数是C++的增强特性之一,用来降低程序的运行时间。当内联函数收到编译器的指示时,即可发生内联:编译器将使用函数的定义体来替代函数调用语句,这种替代行为发生在编译阶段而非程序运行阶段。

值得注意的是,内联函数仅仅是对编译器的内联建议,编译器是否觉得采取你的建议取决于函数是否符合内联的有利条件。如何函数体非常大,那么编译器将忽略函数的内联声明,而将内联函数作为普通函数处理。

#include<stdlib.h>
#include<iostream>
using namespace std;

inline void fun(int i = 30,int j = 20,int k = 10);
inline void fun(double i,double j);

int main(void)
{
    fun(1.11,2.22);
    fun(100,200);

    system("pause");
    return 0;
}

void fun(int i,int j,int k) // 此处可以不用写默认值,写上默认值有的编译器可能会报错。
{
    cout << i << "," << j<< "," << k<< endl;
}

void fun(double i,double j)
{
    cout << i << "," << j << endl;
}

练习:

使用函数的重载完成返回最大值的方法。

现在有一个数组,定义一个方法getMax(),利用函数的重载,分别实现:

1、随意取出数组中的两个元素,传到方法getMax()中,可以返回较大的一个元素。

2、将整个数组传到方法getMax()中,可以返回数组中最大的一个元素。

#include <iostream>
using namespace std;
/**
  *函数功能:返回a和b的最大值
  *a和b是两个整数
  */
int getMax(int a, int b)
{
    return a > b ? a : b;
}

/**
  * 函数功能:返回数组中的最大值
  * arr:整型数组
  * count:数组长度
  * 该函数是对上面函数的重载
  */
int getMax(int *arr,int count)
{
    //定义一个变量并获取数组的第一个元素
    int maxNum = arr[0];
    for(int i = 1; i < count; i++)
    {
        //比较变量与下一个元素的大小
        if(maxNum < arr[i])
        {
            //如果数组中的元素比maxNum大,则获取数组中的值
            maxNum = arr[i];
        }    
    }
    return maxNum;
}

int main(void)
{
    //定义int数组并初始化
    int numArr[3] = {3, 8, 6};

    //自动调用int getMax(int a, int b)
    cout << getMax(numArr, 3) << endl;

    //自动调用返回数组中最大值的函数返回数组中的最大值
    cout << getMax(numArr[0],numArr[2]) << endl;
    return 0;
}

原文链接: https://www.cnblogs.com/chuijingjing/p/9025767.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/273719

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午11:49
下一篇 2023年2月14日 下午11:49

相关推荐