项目:图书库存
Coddy 面向 Rust 开发者的 C++ 课程的第 43 课,共 48 课。
挑战
简单项目第 1 步:实现 Book。构造函数存储书名和非负的副本数量。title 和 available 用于读取状态。borrow 在数量为 0 时返回 false,且不做任何更改;否则数量减 1 并返回 true。give_back 将副本数量加 1。输入的第一行是阶段 1;第二行包含书名、副本数量和尝试次数。打印书名、成功借出的次数和剩余数量。确保后续的 API 占位实现也能通过编译。
可编辑的模块:Book.cpp、Book.hpp、LoanPolicy.cpp、LoanPolicy.hpp、Catalog.cpp、Catalog.hpp、processor.cpp、processor.hpp。每个必需的类型都有各自命名的头文件和实现文件。保留所有公开签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在指定情况下独立检查公开 API 的行为。在 API 内返回值,不要打印内容。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "processor.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
int stage=std::stoi(rows.at(0));
if(stage>=1){Book b("probe",1);if(b.title()!="probe"||b.available()!=1||!b.borrow()||b.borrow())return 31;b.give_back();if(b.available()!=1)return 32;}
if(stage>=2){LoanPolicy p(7,3);if(p.fee(5)!=0||p.fee(7)!=0||p.fee(9)!=6)return 33;}
if(stage>=3){Catalog c;if(!c.add("a",1)||c.add("a",3)||c.add("b",-1)||!c.borrow("a")||c.borrow("a")||c.borrow("missing")||c.available("missing")!=-1||!c.give_back("a")||c.report()!="a:1")return 34;}
if(stage==1){std::istringstream in(rows.at(1));std::string t;int n,k;in>>t>>n>>k;Book b(t,n);int success=0;for(int i=0;i<k;++i)if(b.borrow())++success;std::cout<<b.title()<<" "<<success<<" "<<b.available()<<"\n";}
else if(stage==2){std::istringstream in(rows.at(1));int d,f,e;in>>d>>f>>e;LoanPolicy p(d,f);std::cout<<p.fee(e)<<"\n";}
else if(stage==3){Catalog c;for(size_t i=1;i<rows.size();++i){std::istringstream in(rows[i]);std::string t;int n;in>>t>>n;c.add(t,n);}std::cout<<c.report()<<"\n";}
else if(stage==4){std::cout<<process(std::vector<std::string>(rows.begin()+1,rows.end()))<<"\n";}
}
面向 Rust 开发者的 C++中的所有课
自己练习: C++ 在线编译器