重载与默认值
Coddy 面向 Ruby 开发者的 C++ 课程的第 23 课,共 48 课。
Ruby 不支持重载:如果第二个 def 的名称相同,它会替换第一个定义,因此一个方法必须通过默认值(例如 role = "guest")或关键字参数来处理所有形式的调用。C++ 可以保留多个同名函数,并在编译时根据参数选择其中一个。C++ 的重载通过参数列表区分,而不能只通过返回类型区分。可以使用默认参数,但重叠的重载和默认参数可能会造成歧义。
Ruby
def label(name)
"guest:" + name
end
def label(name, role)
role + ":" + name
end
puts label("Mira", "editor")
begin
puts label("Mira")
rescue ArgumentError => e
puts e.message
end
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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器