保护不变量
Coddy 面向 Kotlin 开发者的 C++ 课程的第 36 课,共 48 课。
Kotlin 成员默认是 public,通常会用 private set 或通过方法访问的私有属性来保护不变量;internal 会将成员开放给整个模块。在 C++ 中,class 成员默认是 private,struct 成员默认是 public。C++ 没有模块可见性,而 friend 会授予指定函数或类访问权限。应公开能够维护不变量的操作,而不是提供对私有状态的可写引用。
Kotlin
class Name {
var text = ""
private set
fun update(s: String): Boolean {
if (s.isEmpty()) return false
text = s
return true
}
}
fun main() {
val n = Name()
println("${n.update("")} ${n.update("oak")} ${n.text}")
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
class Name {std::string text_;public:bool set(const std::string& s){if(s.empty())return false;text_=s;return true;}std::string get()const{return text_;}};
int main(){
Name n;std::cout<<std::boolalpha<<n.set("")<<" "<<n.set("oak")<<" "<<n.get()<<"\n";
}
分别跟踪每个程序。这些示例使用与任务不同的操作或数据来演示这个概念,不假定源程序和目标程序的输出相同。
挑战
简单输入:初始非负容量,然后是请求取出的数量。Stock.take 仅在剩余容量足够时接受非负数量,并返回成功状态;否则状态保持不变。先输出成功状态 true/false,再输出剩余容量。
可编辑模块:Stock.cpp、Stock.hpp。每种必需类型都有各自命名的头文件和实现文件。保留所有公共签名。锁定的 main.cpp 会读取 stdin 并直接调用 API。它还会在指定情况下独立检查公共 API 的行为。在 API 内返回值,不要在其中输出内容。整数输入和结果均在有符号 int 的范围内;除非另有说明,文本均为 ASCII。
亲手试试
#include "Stock.hpp"
#include <iostream>
int main(){
{Stock s(5);if(!s.take(2)||s.take(4)||s.take(-1)||s.remaining()!=3||!s.take(3)||s.remaining()!=0)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,k;in>>n>>k;Stock s(n);bool ok=s.take(k);std::cout<<std::boolalpha<<ok<<" "<<s.remaining()<<"\n";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 C++中的所有课
自己练习: C++ 在线编译器