保护不变量
Coddy 面向 C# 开发者的 C++ 课程的第 36 课,共 48 课。
C# 属性可以验证访问。C++ 通常使用显式的 getter 和修改器方法,而不是属性语法。C++ 私有成员会实施访问控制。应公开能够维护不变式的操作,而不是提供对私有状态的可写引用。
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Box { private int n; public Box(int n) { this.n=n; } public int Double => n*2; }
static void Main() {
Console.WriteLine(new Box(3).Double);
}
}
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";
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 C++中的所有课
自己练习: C++ 在线编译器