C++面向对象入门(二十三)重载自增运算符

重载自增运算符
前置自增运算符: 输出时输出的是自增后的值;
语法:
类名 &operator++() {
函数体
}
注意事项: 返回值类型必须是引用类型, 保证多次使用前置自增保证操作的是同一个对象
后置自增运算符: 输出时先输出的自增前的值
语法:
类名 &operator++(int) {
函数体
}
注意事项: 返回值类型不能是引用类型, 因为返回的是调用对象的拷贝, 已经无法保证操作多次自增操作同一个对象,
而返回引用类型的话, 返回的是局部变量的引用, 在函数调用完成后会释放对象所占的内存
protagonist n.主角;主人公;领导者,倡导者;

代码示例:
#include <iostream>
#include <string>

using namespace std;
/**
 * 重载自增运算符
 *  前置自增运算符: 输出时输出的是自增后的值;
 *  语法:
 *  类名 &operator++() {
 *  函数体
 *  }
 *  注意事项: 返回值类型必须是引用类型, 保证多次使用前置自增保证操作的是同一个对象
 *  后置自增运算符: 输出时先输出的自增前的值
 *  语法:
 *  类名 &operator++(int) {
 *  函数体
 *  }
 *  注意事项: 返回值类型不能是引用类型, 因为返回的是调用对象的拷贝, 已经无法保证操作多次自增操作同一个对象,
 *  而返回引用类型的话, 返回的是局部变量的引用, 在函数调用完成后会释放对象所占的内存
 *  protagonist n.主角;主人公;领导者,倡导者;
 */
class Protagonist {
    friend ostream &operator<<(ostream &cout, const Protagonist &protagonist);
private:
    int level;
    int attack;
    int defend;
    int HP;
    int MP;
public:
    Protagonist():level(1),attack(100),defend(100),HP(100),MP(100){

    }

    //前置自增运算符
    Protagonist &operator++() {
        level++;
        attack += 5;
        defend += 5;
        HP += 20;
        MP += 10;
        return *this;
    }

    //后置自增运算符
    Protagonist operator++(int) {
        Protagonist p(*this);
        level++;
        attack += 5;
        defend += 5;
        HP += 20;
        MP += 10;
        return p;
    }

};

ostream &operator<<(ostream &cout,const Protagonist &protagonist) {
    cout << "{LEVEL:" << protagonist.level << "," << endl;
    cout << "HP:" << protagonist.HP << "," << endl;
    cout << "MP:" << protagonist.MP << "," << endl;
    cout << "ATTACK:" << protagonist.attack << "," << endl;
    cout << "DEFEND:" << protagonist.defend << "}" ;
}

void test1() {
    Protagonist protagonist;
    cout<< protagonist++ <<endl;
    cout<< protagonist << endl;
}
int main() {
    test1();
    system("pause");

    return 0;
}

 

 
posted @ 2020-08-21 11:04  DNoSay  阅读(424)  评论(0编辑  收藏  举报