Skip to content

默认参数 ​

默认参数允许在函数声明时为参数指定默认值,调用时可以省略这些参数。

cpp
void greet(const std::string &name = "World") {
    std::cout << "Hello, " << name << "!" << std::endl;
}

int main() {
    greet();           // 输出: Hello, World!
    greet("Alice");    // 输出: Hello, Alice!
}

使用规则 ​

从右向左依次指定 ​

默认参数必须从右向左连续声明,不能“间隔使用”。

cpp
// 正确:默认参数在右边
void func(int a, int b = 10, int c = 20);

// 错误:默认参数不能在非默认参数左边
void bad(int a = 1, int b);  // 编译错误!

声明和定义不可重复指定 ​

函数声明和函数实现中,只能有一处指定默认值,不能同时存在。

TIP

默认参数只写在声明处(通常是头文件)。

cpp
// 声明处指定默认值
void setup(int port = 8080);

// 定义处不再重复指定
void setup(int port) {
    // ...
}

典型用法 ​

cpp
// 1. 可选参数
void createWindow(int width = 800, int height = 600);
createWindow();           // 800x600
createWindow(1024);       // 1024x600
createWindow(1024, 768);  // 1024x768

// 2. 简化 API
void connect(const std::string &host = "localhost",
            int port = 80,
            bool ssl = false);

// 常用场景:只需指定 host
connect("example.com");

// 完整指定
connect("example.com", 443, true);

注意事项 ​

默认参数与函数重载可能产生歧义 ​

cpp
void print(int x = 0);
void print(const std::string &s = "");

print();  // 编译错误!歧义:调用哪个?

默认值可以是表达式 ​

cpp
int getValue(int base = rand() % 100);  // 每次调用计算默认值
int getArray(int size = 10);            // 常量表达式

静态变量可用作默认值 ​

cpp
int getID() {
    static int nextID = 1000;
    return nextID++;
}

void registerUser(const std::string &name, int id = getID());