重载与默认值
Coddy 面向 R 开发者的 C++ 课程的第 23 课,共 48 课。
R 为函数提供默认参数和命名参数,例如 role = "guest";再次定义 label 会替换旧的绑定,因此普通 R 函数没有重载,而 S3 方法会根据第一个参数的类进行分派。C++ 重载的区别在于参数列表不同,而不能只靠返回类型区分。可以使用默认参数,但重叠的重载和默认参数可能会造成歧义。
R
label <- function(name, role = "guest") {
paste0(role, ":", name)
}
print(label("Mira"))
print(label("Mira", role = "editor"))
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
std::string label(std::string n,std::string r){return r+":"+n;}
std::string label(std::string n){return label(n,"guest");}
int main(){
std::cout<<label("Mira")<<"\n"<<label("Mira","editor")<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来说明概念,不假设源程序和目标程序的输出相同。
挑战
简单输入:非负价格和数量。实现两个 cost 重载:一个参数时返回价格,两个参数时返回价格乘以数量。驱动程序会调用两者。
在 exercise.hpp 和 exercise.cpp 中实现声明的 API。两个文件都可以编辑;保留公共函数签名。锁定的 main.cpp 会读取标准输入,并直接调用 API。文中说明时,它还会独立检查公共 API 的行为。API 中应返回值,而不是打印内容。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int p,q;in>>p>>q;std::cout<<cost(p)<<" "<<cost(p,q)<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 C++中的所有课
自己练习: C++ 在线编译器