方法与 const 访问
Coddy 面向 Ruby 开发者的 C++ 课程的第 34 课,共 48 课。
和 C++ 一样,Ruby 会隐式传递接收者:在方法内部,self 和 @name 无需参数就能引用当前对象。Ruby 没有 const 方法;最接近的工具是 freeze,它会让整个对象在运行时拒绝修改,并触发 FrozenError。C++ 会将实例方法隐式地接收这个对象。const 成员函数可以通过 const 引用调用,编译器会在程序运行前进行检查。
Ruby
class Badge
attr_reader :name
def initialize(name)
@name = name
end
def rename(name)
@name = name
end
end
badge = Badge.new("old")
badge.rename("new")
badge.freeze
begin
badge.rename("late")
rescue FrozenError
puts "frozen"
end
puts badge.name
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Badge {std::string name;void rename(std::string n){name=std::move(n);}std::string label()const{return name;}};
int main(){
Badge b{"old"};b.rename("new");const Badge& r=b;std::cout<<r.label()<<"\n";
}
分别跟踪每个程序的执行过程。这些示例使用与任务不同的操作或数据来展示这一概念,不要求源程序和目标程序的输出相同。
挑战
简单输入:初始值和两个带符号的变更。Counter.add 会修改实例;value 是 const,并返回当前状态。
可编辑模块:Counter.cpp、Counter.hpp。每种必需类型都有自己的命名头文件和实现。保留所有公共签名。锁定的 main.cpp 会读取标准输入并直接调用 API。它还会在指定情况下独立检查公共 API 的行为。在 API 内返回值,而不是打印。整数输入和结果都在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "Counter.hpp"
#include <iostream>
int main(){
{Counter a(2),b(9);a.add(5);const Counter& r=a;if(r.value()!=7||b.value()!=9)return 21;}
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,a,b;in>>n>>a>>b;Counter c(n);c.add(a);c.add(b);std::cout<<c.value()<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Ruby 开发者的 C++中的所有课
自己练习: C++ 在线编译器