C++缺省参数详解
一、什么是缺省参数?
概念:
缺省参数是声明或定义函数时为函数的参数指定一个缺省值。在调用该函数时,如果没有指定实
参则采用该形参的缺省值,否则使用指定的实参。
举例:
//缺省参数
void Func(int a = 0)
{
cout<<a<<endl;
}
int main()
{
Func(); // 没有传参时,使用参数的默认值
Func(10); // 传参时,使用指定的实参
return 0;
}
二、缺省参数的分类
1、全缺省
概念:声明的函数的参数都有缺省值
举例:
void Func(int a = 10, int b = 20, int c = 30)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
2、半缺省参数
概念:记住这里的半不代表一半,而是从右往左依次给一部分的缺省值。
举例:
void Func(int a, int b = 10, int c = 20)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
三、缺省参数的注意事项
1、 半缺省参数必须从右往左依次来给出,不能间隔着给
举例:
// 赋值 到这边(左边)<--------- 从这边(右边)
void Func(int a, int b = 10, int c = 20)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
//不能这样赋值
void Func(int a=1, int b = 10, int c)
{
cout<<"a = "<<a<<endl;
cout<<"b = "<<b<<endl;
cout<<"c = "<<c<<endl;
}
2、缺省参数不能在函数声明和定义中同时出现
举例:
//头文件:Stack.h
#pragma once
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
struct Stack
{
int* a;
int size;
int capacity;
};
//声明
void StackInit(struct Stack* ps, **int n = 4**);//缺省参数只能声明的时候给
void StackPush(struct Stack* ps, int x);
//源文件:Stack.cpp
#include"Stack.h"
//定义
void StackInit(struct Stack* ps, int n ) //定义时不能给缺省参数,否则报错,编译器无法区分
{
ps->a = (int*)malloc(sizeof(int) * n);
}
void StackPush(struct Stack* ps, int x)
{
}
//源文件:Test.cpp
#include"Stack.h"
int main()
{
struct Stack st1;
StackInit(&st1, 100);
struct Stack st2;
StackInit(&st2, 10);
struct Stack st3;
StackInit(&st3);
return 0;
}
3、缺省值必须是常量或者全局变量
举例:
//常量
void printMessage(const std::string& message = "Hello")
{
std::cout << message << std::endl;
}
常量的大致分类:
1.字面常量(Literal Constants):如整数常量、浮点数常量、字符常量等。
2.const 修饰的变量:通过 const 关键字声明的变量,在程序运行过程中其数值不可改变。
3.枚举常量(Enum Constants):通过枚举类型定义的常量。
4.constexpr 变量:在编译时就能得到计算结果的常量表达式。
5.字符串常量:用双引号括起来的字符串,如 “Hello, World!”。
6.全局常量:在全局作用域下定义的常量。
7.类静态成员常量:在类中使用 static 关键字定义的静态成员常量。
8.函数中的常量:在函数中使用 const 关键字定义的局部常量。
//全局变量
int defaultValue = 10;
void printNumber(int number = defaultValue)
{
std::cout << number << std::endl;
}