cpp 函数的默认参数
时间: 2023-11-06 16:06:55 浏览: 46
C++ 函数的默认参数是指在函数声明时,为某个参数设置一个默认值,如果在函数调用时没有给该参数传递实参,则会使用默认值作为其实参。
例如下面的代码定义了一个带有默认参数的函数:
```cpp
void print(int x, int y = 10) {
cout << "x: " << x << ", y: " << y << endl;
}
```
在调用该函数时,可以只传递一个参数,也可以传递两个参数:
```cpp
print(5); // 输出: x: 5, y: 10
print(5, 20); // 输出: x: 5, y: 20
```
如果在函数声明时为某个参数设置了默认值,在函数定义时也必须为该参数设置默认值,例如:
```cpp
void print(int x, int y = 10) {
cout << "x: " << x << ", y: " << y << endl;
}
// 在函数定义时也必须为 y 参数设置默认值
void print(int x, int y) {
cout << "x: " << x << ", y: " << y << endl;
}
```
相关问题
cpp 函数可以有默认参数吗?
是的,C++函数可以有默认参数。在函数定义中,可以给参数设置默认值,如果函数调用时没有传递该参数,则使用默认值。例如:
```
void printMessage(string message = "Hello World!") {
cout << message << endl;
}
```
在这个例子中,函数 `printMessage` 有一个默认参数 `message`,默认值为 `"Hello World!"`。如果在调用函数时不传递参数,则使用默认值输出 `"Hello World!"`。例如:
```
printMessage(); // 输出 "Hello World!"
printMessage("Hi there!"); // 输出 "Hi there!"
```
数组去重 cpp函数
在C++中,可以使用以下函数来对数组进行去重操作:
```cpp
#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> removeDuplicates(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end()); // 先对数组进行排序
nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); // 使用unique函数去除重复元素
return nums;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4, 2, 3, 5};
std::vector<int> result = removeDuplicates(nums);
for (int num : result) {
std::cout << num << " ";
}
return 0;
}
```
上述代码中,`removeDuplicates`函数接受一个整数类型的向量作为参数,并返回去重后的向量。函数内部首先对数组进行排序,然后使用`std::unique`函数去除重复元素,最后使用`erase`函数将重复元素后面的部分删除。在`main`函数中,我们定义了一个测试用例,并输出去重后的结果。