c++ - 有没有一种通用的方法来实现不变量?
问题描述
这是一个基本示例,我想添加不变量,例如我的年龄不能低于 0。
#include "InvariantTest.h"
#include <iostream>
#include <string>
using namespace std;
int age;
string name;
void setAge(int a) {
age = a;
}
void setName(string n) {
name = n;
}
string getNameandAge() {
string both;
both = name + to_string(age);
return both;
}
我找不到如何在 C++ 中实现不变量的规范。
解决方案
从标签描述:
在计算机科学中,谓词被称为操作序列的不变量,前提是:如果谓词在序列开始之前为真,则在序列结束时为真。
例如,谓词age > 0
。例如,一系列操作
setAge(42);
另一个
setAge(-123);
为确保不违反不变量,您可以将条件添加到setAge
:
void setAge(int a) {
if (a > 0) age = a;
}
您可以自行决定抛出异常、终止程序、采取任何其他操作,或者在分配值违反不变量时默默地忽略该值。没有“规范”,因为它取决于您要采取的操作以及调用者可以从传递无效参数中得到什么。
你也可以使age
无符号,那么不变量age >= 0
总是成立。
推荐阅读
- asp.net-core - ASP.NET CORE 和 BLAZOR:重置密码
- php - 如何在 Laravel 6 中使用 DB::raw 将基于关系的文件放入 CONCAT?
- java - 在java中读取文件的特定部分
- c# - 使用 WPF 在框架中加载页面。框架可以重定向到页面。但设计未加载
- c++ - cmake add_custom_command + Xcode:多输出=多命令调用
- java - 如何在 AndroidStudio 中保存按钮的状态?
- .net - AWS DynamoDb - 更新列表中的特定地图 (.NET)
- reactjs - 在浏览器中显示失败的重建开发 npm/react/gatsy 错误
- magento - 用于 Magento 2 开发的 Docker
- javascript - 谷歌表格脚本 - onChange