C++默认实参

某些函数中有这样一种形参,函数多次调用中都会被赋予一个相同的值,此时,我们可以在定义函数时给该形参赋予一个默认值称为函数的默认实参,调用默认实参的函数时,可以包含该实参,也可以省略该实参,省略该实参时,会使用默认实参。

函数调用实参时按其位置解析,默认实参负责填补函数调用缺少的尾部实参。在设计含有默认实参的函数时,其中一项任务时合理设置形参的顺序,尽量让不怎么使用默认值的形参出现在前面,而那些经常使用默认值的形参出现在后面。

#include "stdafx.h"
#include <cstdio>
#include <iostream>
 
void createScreen(int height = 100, int width = 200, const char* name = "screen")
{
    std::cout << "height=" << height << ",width=" << width << ",name=" << name << std::endl;
}

int main()
{
    createScreen();
    createScreen(10);
    createScreen(2,5);
    createScreen(20, 50,"bigScreen");
    system("pause");
    return 0;
}
height=100,width=200,name=screen
height=10,width=200,name=screen
height=2,width=5,name=screen
height=20,width=50,name=bigScreen

默认实参声明

在给定的作用域中,一个形参只能被赋予一次默认实参,换句话说,函数的后续声明只能为之前那些没有默认值的形参添加默认实参,而且该形参右侧的所有形参必须都有默认值。通常应该在函数声明中指定默认实参,并将该声明放在合适的头文件中。

//Screen.h
#pragma once

void createScreen(int height, int width, const char* name = "screen");

错误,重定义了默认参数name

#include "stdafx.h"
#include <cstdio>
#include <iostream>
#include "Screen.h"
 

void createScreen(int height, int width, const char* name="screen")
{
    std::cout << "height=" << height << ",width=" << width << ",name=" << name << std::endl;
}

int main()
{
    createScreen();
    createScreen(10);
    createScreen(2,5);
    createScreen(20, 50,"bigScreen");
    system("pause");
    return 0;
}

正确,添加了默认实参

#include "stdafx.h"
#include <cstdio>
#include <iostream>
#include "Screen.h"
 
void createScreen(int height=10, int width=100, const char* name)
{
    std::cout << "height=" << height << ",width=" << width << ",name=" << name << std::endl;
}

int main()
{
    createScreen();
    createScreen(10);
    createScreen(2,5);
    createScreen(20, 50,"bigScreen");
    system("pause");
    return 0;
}

默认实参初始值

除了局部变量,只要表达式能转换成形参所需的类型,该表达式就能作为默认实参。

#include "stdafx.h"
#include <cstdio>
#include <iostream>

int g_defaultHeight = 10;
int g_defaultWidth = 100;
const char* g_defaultScreenName = "screen";

const char* getScreenName()
{
    return g_defaultScreenName;
}
 
void createScreen(int height= g_defaultHeight, int width= g_defaultWidth, const char* name= getScreenName())
{
    std::cout << "height=" << height << ",width=" << width << ",name=" << name << std::endl;
}

int main()
{
    createScreen();
    g_defaultHeight = 20;
    g_defaultWidth = 200;
    g_defaultScreenName = "bigScreen";
    createScreen();
    system("pause");
    return 0;
}
height=10,width=100,name=screen
height=20,width=200,name=bigScreen
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容