共享静态成员
Coddy 面向 Python 开发者的 C++ 课程的第 35 课,共 48 课。
Python 类属性会参与动态查找,也可能被实例上的同名属性遮蔽。C++ 静态成员需要显式声明。C++ 静态成员属于类,而不是实例。静态函数没有 this 指针。
Python
class Bag:
category = "tools"
def __init__(self):
self.items = []
a, b = Bag(), Bag()
a.category = "books"
print(a.category, b.category, Bag.category)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_ 开始,将连续 ID 从 1 开始分配。reset 将 next_ 重置为 1。驱动程序会创建 n 张票,并返回它们的 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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Python 开发者的 C++中的所有课
自己练习: C++ 在线编译器