共享静态成员
Coddy 面向 R 开发者的 C++ 课程的第 35 课,共 48 课。
R 类没有类级存储:S3 类只是属性中的一个名称,因此所有对象共享的状态通常保存在环境中。环境可变,修改时不会被复制;也可以保存在包命名空间中。C++ 静态成员需要显式声明。C++ 静态成员属于类,而不是实例。静态函数没有 this 指针。
R
registry <- new.env()
registry$count <- 0
make_bag <- function() {
registry$count <- registry$count + 1
list(id = registry$count)
}
a <- make_bag()
b <- make_bag()
cat(a$id, b$id, registry$count, "\n")
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Scale {static int double_value(int n){return 2*n;}};
int main(){
std::cout<<Scale::double_value(6)<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这个概念,不假设源代码和目标代码的输出相同。
挑战
简单输入:非负的对象数量。Ticket 从共享的 next_ 开始,为对象分配从 1 开始的连续 ID。reset 会将 next_ 重置为 1。驱动程序会创建 n 个 Ticket,并返回它们的 ID 总和。
可编辑模块:Ticket.cpp、Ticket.hpp。每种必需的类型都有自己命名的头文件和实现文件。保留所有公共签名。锁定的 main.cpp 会读取标准输入,并直接调用 API。它还会在有说明的情况下独立检查公共 API 的行为。在 API 中返回值,不要打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "Ticket.hpp"
#include <iostream>
int main(){
{Ticket::reset();Ticket a,b;if(a.id()!=1||b.id()!=2)return 21;Ticket::reset();Ticket c;if(c.id()!=1||a.id()!=1)return 22;}
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 n;in>>n;Ticket::reset();int sum=0;for(int i=0;i<n;++i){Ticket t;sum+=t.id();}std::cout<<sum<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 R 开发者的 C++中的所有课
自己练习: C++ 在线编译器