
Student& operator++(Student& s) , 返回的是对象引用 , 参数正常 ;Student operator++(Student& s, int) , 返回的事对象值 , 参数列表最后一位需要添加 int 类型的占位参数 ;由此可见 , 后置运算符重载的难度高于前置运算符 ;
使用 全局函数 实现 后置 ++ 自增运算符重载 :
operate++ ;operate++operator++(Student& s, int)Student operator++(Student& s, int)// 使用 全局函数 实现 后置 ++ 自增运算符重载
// 重载 后置 ++ 运算符
// 实现 1 个 Student 对象 自增运算
// 先使用 参数中的 Student& s 对象 , 再自增
// 因此 Student& s 对象是需要自增的
// 但是使用的对象 就是 返回的对象, 必须是没有自增的对象
// 这里使用 ret 保存 s 对象值 , 然后返回该 ret 值
// s 对象中的值自增
// 返回的是一个新 Student 对象
Student operator++(Student& s, int)
{
Student ret = s;
s.age++;
s.height++;
return ret;
};使用 成员函数 实现 后置 – 自减运算符重载 :
operate-- ;operate--operator--(int)Student operator--(int)public:
// 使用 成员函数 实现 后置 -- 自减运算符重载
// 重载 后置 -- 运算符
// 实现 1 个 Student 对象 自减运算
// 先使用 this 指针指向的对象 , 再自减
// 因此 this 指针指向的对象 是需要自减的
// 但是使用的对象 就是 返回的对象, 必须是没有自减的对象
// 这里使用 ret 保存 this 指针指向的对象值 , 然后返回该 ret 值
// this 指针指向的对象值自减
// 返回的是一个新 Student 对象
Student operator--(int)
{
Student ret = *this;
this->age--;
this->height--;
return ret;
};代码示例 :
#include "iostream"
using namespace std;
class Student
{
public:
// 带参构造函数 , 为参数设置默认值
Student(int age = 1, int height = 1)
{
this->age = age;
this->height = height;
};
public:
// 打印类数据
void print()
{
cout << "age = " << age << " , height = " << height << endl;
};
public:
// 使用 成员函数 实现 后置 -- 自减运算符重载
// 重载 后置 -- 运算符
// 实现 1 个 Student 对象 自减运算
// 先使用 this 指针指向的对象 , 再自减
// 因此 this 指针指向的对象 是需要自减的
// 但是使用的对象 就是 返回的对象, 必须是没有自减的对象
// 这里使用 ret 保存 this 指针指向的对象值 , 然后返回该 ret 值
// this 指针指向的对象值自减
// 返回的是一个新 Student 对象
Student operator--(int)
{
Student ret = *this;
this->age--;
this->height--;
return ret;
};
public:
int age; // 年龄
int height; // 身高
};
// 使用 全局函数 实现 前置 ++ 自增运算符重载
// 重载 前置 ++ 运算符
// 实现 1 个 Student 对象 自增运算
// 由于 参数中的 Student& s 中的属性发生了变化
// 返回时仍需要返回 Student& s 参数本身
Student& operator++(Student& s)
{
s.age++;
s.height++;
return s;
};
// 使用 全局函数 实现 后置 ++ 自增运算符重载
// 重载 后置 ++ 运算符
// 实现 1 个 Student 对象 自增运算
// 先使用 参数中的 Student& s 对象 , 再自增
// 因此 Student& s 对象是需要自增的
// 但是使用的对象 就是 返回的对象, 必须是没有自增的对象
// 这里使用 ret 保存 s 对象值 , 然后返回该 ret 值
// s 对象中的值自增
// 返回的是一个新 Student 对象
Student operator++(Student& s, int)
{
Student ret = s;
s.age++;
s.height++;
return ret;
};
int main() {
// 自定义类型相加
Student s1(10, 120), s2(18, 170);
Student s3, s4, s5;
++s1;
s1.print();
s2++;
s2.print();
s2--;
s2.print();
// 控制台暂停 , 按任意键继续向后执行
system("pause");
return 0;
};执行结果 :
age = 11 , height = 121
age = 19 , height = 171
age = 18 , height = 170
请按任意键继续. . .