共享静态成员
Coddy 面向 Ruby 开发者的 C++ 课程的第 35 课,共 48 课。
在 Ruby 中,类本身就是一个对象:def self.count 会在该对象上定义一个方法,而 @@variable 由类、它的子类和每个实例共享,并在运行时通过查找找到。C++ 静态成员需要显式声明。C++ 静态成员属于类,而不是某个实例。静态函数没有 this 指针。
Ruby
class Bag
@@count = 0
def self.count
@@count
end
def initialize
@@count += 1
end
end
Bag.new
Bag.new
puts Bag.countC++
#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_ 开始分配连续 ID,起始值为 1。reset 会将 next_ 重置为 1。驱动程序会创建 n 个 Ticket,并返回它们的 ID 总和。
可编辑模块:Ticket.cpp、Ticket.hpp。每种必需类型都有各自命名的头文件和实现文件。保留所有公开签名。锁定的 main.cpp 会读取 stdin,并直接调用 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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器