有一个明显的理由来为 int 设置一个类,因为 int 本身不允许缺少任何值。以 JSON 消息为例。它可以包含一个名为“foo”的对象的定义,以及一个名为“bar”的整数,例如:
{"foo": {"bar": 0}}
这意味着“bar”等于0(零),但是如果省略“bar”,像这样:
{"foo": {}}
现在有了“bar”不存在的意思,这是完全不同的意思,不能单独用int来表示。在过去,如果出现这种情况,一些程序员会使用单独的标志,或使用特定的整数值来表示该值未提供、未定义或不存在。但是不管你怎么称呼它,一个更好的方法是有一个整数类,它定义了功能并使其可重用和一致。
另一种情况是数据库表在创建后的某个时间添加了一个整数列。在添加新列之前添加的记录将返回 null,这意味着不存在任何值,并且在创建列之后添加的记录将返回一个值。您可能需要对 null 值与 0(零)采取不同的操作。
所以这里是 int 或 string 类的开始。但在我们开始编写代码之前,让我们先看看它的用法,因为这就是为什么你首先要创建这个类,从长远来看让你的生活更轻松。
int main(int argc, char **argv) {
xString name;
xInt age;
std::cout<< "before assignment:" << std::endl;
std::cout<< "name is " << name << std::endl;
std::cout<< "age is " << age << std::endl;
// some data collection/transfer occurs
age = 32;
name = "john";
// data validation
if (name.isNull()) {
throw std::runtime_error("name was not supplied");
}
if (age.isNull()) {
throw std::runtime_error("age was not supplied");
}
// data output
std::cout<< std::endl;
std::cout<< "after assignment:" << std::endl;
std::cout<< "name is " << name << std::endl;
std::cout<< "age is " << age << std::endl;
return 0;
}
这是程序的示例输出:
before assignment:
name is null
age is null
after assignment:
name is john
age is 32
请注意,当 xInt 类的实例尚未赋值时,
好的,下面是上面 main 方法的类代码:
#include <iostream>
#include <string>
class xInt {
private:
int _value=0;
bool _isNull=true;
public:
xInt(){}
xInt(int value) {
_value=value;
_isNull=false;
}
bool isNull(){return _isNull;}
int value() {return _value;}
void unset() {
_value=0;
_isNull=true;
}
friend std::ostream& operator<<(std::ostream& os, const xInt& i) {
if (i._isNull) {
os << "null";
} else {
os << i._value;
}
return os;
}
xInt& operator=(int value) {
_value=value;
_isNull=false;
return *this;
}
operator const int() {
return _value;
}
};
class xString {
private:
std::string _value;
bool _isNull=true;
public:
xString(){}
xString(int value) {
_value=value;
_isNull=false;
}
bool isNull() {return _isNull;}
std::string value() {return _value;}
void unset() {
_value.clear();
_isNull=true;
}
friend std::ostream& operator<<(std::ostream& os, const xString& str) {
if (str._isNull) {
os << "null";
} else {
os << str._value;
}
return os;
}
xString& operator<<(std::ostream& os) {
os << _value;
return *this;
}
xString& operator=(std::string value) {
_value.assign(value);
_isNull=false;
return *this;
}
operator const std::string() {
return _value;
}
};
有些人可能会说,哇,与只说 int 或 string 相比,这相当难看,是的,我同意它非常罗嗦,但请记住,你只编写一次基类,然后从那时起,你的代码你每天阅读和写作看起来更像我们第一次看到的主要方法,而且非常简洁明了,同意吗?接下来,您将要学习如何构建共享库,以便将所有这些通用类和功能放入可重用的 .dll 或 .so 中,这样您就只编译业务逻辑,而不是整个宇宙。 :)