我们可以通过封装一个新的C++类来实现新的数据类型的定义。
目录
优点:
- 用新的名字代替原有数据类型名
- 可以对这种数据类型赋予专属的方法
比如我们可以创建一个intx类
class intx {
private:
int num;
public:
intx(int x) : num(x) {}
void show() const {
std::cout << num << std::endl;
}
void reset() {
num = 0;
}
// 使用int类型来获取num的值,但不会修改对象状态
int use() const {
return num;
}
// 改变数值
void change(int x) {
num = x;
}
// 自增,返回对原对象的引用以支持链式调用
intx& self_increase() {
++num;
return *this;
}
// 自减,返回对原对象的引用以支持链式调用
intx& self_reduction() {
--num;
return *this;
}
// 重载++运算符(前缀版本)
intx& operator++() {
++num;
return *this;
}
// 重载++运算符(后缀版本)
intx operator++(int) {
intx temp = *this;
++(*this);
return temp;
}
// 重载--运算符(前缀版本)
intx& operator--() {
--num;
return *this;
}
// 重载--运算符(后缀版本)
intx operator--(int) {
intx temp = *this;
--(*this);
return temp;
}
};
主要方法:
下面我就来介绍一下intx的方法有哪些: