1. c++重载递增运算和左移运算

代码

#include <iostream>
#include <string>
using namespace std;
//
class Person{
    friend ostream& operator<<(ostream &cout,Person p);
public:
    
    Person(int a){
        this->a = a;
    }
    Person& operator++(){
        this->a++;
        cout<<"前置++:"<<this<<endl;
        return *this;
    }
    Person operator++(int){
        Person temp = *this;
        cout<<"temp: "<<&temp<<endl;
        cout<<"后置++: "<<this<<endl;
        this->a++;
        return temp;
    }

private:
    int a;
};

ostream& operator<<(ostream &cout,Person p){
    cout<<"Person.a: "<<p.a<<endl;;
    cout<<"cout中p: "<<&p<<endl;
    return cout;
}
int main(){
    Person p(10);
    cout<<"main中初始化p: "<<&p<<endl;
    ++p;
    cout<<endl;
    p++;

//    cout<<p++<<endl;

}

输出结果为:

 

注意以下代码段

ostream& operator<<(ostream &cout,Person p)
这里第二个参数为Person P。
若在main函数中运行
cout<<p++<<endl;
cout<<++p<<endl;
重载前置++(++p)时,参数为Person p 和 Person &p都不会报错
但是在 重载后置++(p++)时,参数为Person &p就会报错
这是因为Person &p为传递地址,重载后置++时,由于 Person temp = *this;return temp;返回的是局部类temp,在函数调用结束后就释放了temp的地址 。cout<<p++<<endl;将会打印temp的地址,固会报错。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值