首页 > 解决方案 > 有没有一种通用的方法来实现不变量?

问题描述

这是一个基本示例,我想添加不变量,例如我的年龄不能低于 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++ 中实现不变量的规范。

标签: c++invariants

解决方案


从标签描述:

在计算机科学中,谓词被称为操作序列的不变量,前提是:如果谓词在序列开始之前为真,则在序列结束时为真。

例如,谓词age > 0。例如,一系列操作

setAge(42);

另一个

setAge(-123);

为确保不违反不变量,您可以将条件添加到setAge

void setAge(int a) {
    if (a > 0) age = a;
}

您可以自行决定抛出异常、终止程序、采取任何其他操作,或者在分配值违反不变量时默默地忽略该值。没有“规范”,因为它取决于您要采取的操作以及调用者可以从传递无效参数中得到什么。

你也可以使age无符号,那么不变量age >= 0总是成立。


推荐阅读