Menu
CoddyTech

共享静态成员

Coddy 面向 Lua 开发者的 C++ 课程的第 35 课,共 48 课。

在 Lua 中,通过 __index 查找,类表中的字段会被每个实例共享;但在实例上赋值相同的键会创建单独的字段并遮蔽它,因为 __index 只影响读取。C++ 的静态成员需要显式声明。C++ 静态成员属于类,而不是实例;没有对象持有它的副本,因此无法遮蔽它。静态函数没有 this 指针。

Lua

local Bag = {}
Bag.__index = Bag
Bag.category = "tools"
function Bag.new()
  return setmetatable({ items = {} }, Bag)
end
local a, b = Bag.new(), Bag.new()
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";
}

分别跟踪每个程序。这些示例使用与任务不同的操作或数据来展示这个概念,不要假设源程序和目标程序的输出相同。

challenge icon

挑战

简单

输入:非负对象数量。Ticket 从共享变量 next_ 开始分配连续 ID,起始值为 1。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";
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Lua 开发者的 C++中的所有课

自己练习: C++ 在线编译器