【C++】C++入门 缺省参数


一、缺省参数

1、C/C++函数空参数的区别

  • 在C语言中,函数没有指定参数列表时,默认可以接收任意多个参数;
#include<stdio.h>
void Test()
{
    
    
}
int main()
{
    
    
    Test(10);
    Test(10, "hello");
    return 0;
}

在这里插入图片描述

  • 在C++中,因为有严格的参数类型检测,所以函数没有参数列表时,默认为void,不接收任何参数。
#include<iostream>
using namespace std;

void Test()
{
    
    

}
int main()
{
    
    
    Test(10);
    Test(10, "hello");
    return 0;
}

在这里插入图片描述

2、缺省参数概念

缺省参数是声明或定义函数时为函数的参数指定一个缺省值。在调用该函数时,如果没有指定实参则采用该形参的缺省值,否则使用指定的实参。

#include<iostream>
using namespace std;
void Func(int a = 0)//给参数a指定一个缺省值
{
    
    
	cout << a << endl;
}
int main()
{
    
    
	Func(); // 没有传参时,使用参数的默认值,输出为0
	Func(10); // 传参时,使用指定的实参,输出为10
	return 0;
}

在这里插入图片描述

3、缺省参数分类

  • 全缺省参数
void Func(int a = 10, int b = 20, int c = 30)
{
    
    
   cout<<"a = "<<a<<endl;
   cout<<"b = "<<b<<endl;
   cout<<"c = "<<c<<endl;
}
  • 半缺省参数
void Func(int a, int b = 10, int c = 20)//此时a必须要接受到参数
{
    
    
   cout<<"a = "<<a<<endl;
   cout<<"b = "<<b<<endl;
   cout<<"c = "<<c<<endl;
}

注意:半缺省参数必须从右往左依次缺省,不能间隔着缺省

void Func(int a=10, int b , int c = 20)//报错
{
    
    
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
}

在这里插入图片描述

二、注意事项

  1. 半缺省参数必须从右往左依次来给出,不能间隔着给
#include<iostream>
using namespace std;
void Func(int a=10, int b=20 , int c = 30)
{
    
    
	cout << "a = " << a << endl;
	cout << "b = " << b << endl;
	cout << "c = " << c << endl;
}
int main()
{
    
    
	Func(1, 2, 3);
	Func(1, 2);
	Func(1, ,3);//报错
	return 0;
}
  1. 缺省参数不能在函数声明和定义中同时出现,应该在声明中给予缺省值
#include<iostream>
using namespace std;
void Func(int a = 10);
int main()
{
    
    
	
	Func();
	return 0;
}
void Func(int a = 10)
{
    
    
	cout << "a = " << a << endl;
}

在这里插入图片描述

  1. 缺省值必须是常量或者全局变量
  2. C语言不支持(编译器不支持)

猜你喜欢

转载自blog.csdn.net/qq_65207641/article/details/128850465