编程语言基础:用“收集器”理解各种语言(C++、Java、Python)中的可变参数!

时间:2023-06-09 14:59:20

索引:

1、Java

public class Animal {
// 接受可变参数的方法
void eat(String... Objects) {
for (String x : Objects) {
System.out.println("我吃了一个" + x + "!");
}
}
// 调用示例
public static void main(String[] args) {
Animal dada = new Animal();
dada.eat("苹果", "南瓜饼", "土豆");
}
/* outputs:
我吃了一个苹果!
我吃了一个南瓜饼!
我吃了一个土豆!
*/
}

2、Python

>>> def f(*args, **kw):
... print(args)
... print(kw)
...
>>> f(1, 2, 3, name = 'dada', age = 5)
(1, 2, 3)
{'age': 5, 'name': 'dada'}

可以理解为将位置参数收集为一个叫做args的tuple,将关键字参数收集为一个叫做kw的dict。

PS. 位置参数、关键字参数应该是Python特有的...

3、C++

#include <iostream>
#include <initializer_list>
using namespace std;
int sum(initializer_list<int> il)
{
int sum = ;
for (auto &x : il) {
sum += x;
}
return sum;
}
int main()
{
cout << sum({, , , , }) << endl; // output=15
return ;
}

4、js

const ilike = (...foods) => {
for (let x of foods) {
console.log(`i like eat ${x}`);
}
};
ilike('apple', 'chicken');
=> i like eat apple
=> i like eat chicken

PS. 请忽略语法错误...

三点号还能这么用:

let words = ["never", "fully"];
console.log(["will", ...words, "understand"]);
// → ["will", "never", "fully", "understand"]