C++运算符重载++,--

C++自增自减运算共有四种:前缀自增,前缀自减,后缀自增,后缀自减。
C++在重载这四种运算符的过程中通过在后缀时传入一个无用的int参数,前缀时无参数来区分。
前缀的自增自减运算返回操作之后的值,所以应该返回引用,而后缀的自增自减运算返回操作前的值所以应该返回对象的副本。

通过具体的例子可以看看怎样进行++,–的重载。

//NumCell.h
#pragma once
#include <iostream>

using namespace std;

class NumCell
{
    int num;
public:
    NumCell();
    ~NumCell();
    NumCell& operator++();
    NumCell& operator--();
    NumCell operator++(int);
    NumCell operator--(int);
    void setNum(int num);
    friend ostream& operator<<(ostream& os, NumCell& num);
};


//NumCell.cpp
#include "NumCell.h"

NumCell::NumCell()
{
}


NumCell::~NumCell()
{
}

void NumCell::setNum(int num){
    this->num = num;
}
//前缀
NumCell& NumCell::operator++(){
    this->num++;
    return *this;
}
NumCell& NumCell::operator--(){
    this->num--;
    return *this;
}
//后缀
NumCell NumCell::operator++(int){
    NumCell nc = *this;
    this->num++;
    return nc;
}
NumCell NumCell::operator--(int){
    NumCell nc = *this;
    this->num--;
    return nc;
}

ostream& operator<<(ostream& os, NumCell& num){
    os << num.num << endl;
    return os;
}

//main.cpp
#include "NumCell.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    NumCell nc;

    nc.setNum(99);
    cout << nc; //99
    nc--;
    cout << nc; //98
    cout << nc--; //98
    cout << nc++; //98
    cout << ++nc; //99
    cout << --nc; //98

    system("pause");
    return 0;
}

程序的输出结果就像main()函数中注释的一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值