AllBull 2022-01-14 17:21 采纳率: 40%
浏览 18
已结题

c++中重载自增时 cout与++出错

img

完整代码如下:


#include <iostream>
using namespace std;

class Person3 {
    friend ostream& operator<<(ostream& cout, Person3& p1);
public:


    Person3(int a, int b) :m_A(a), m_B(b) {
    }

    Person3& operator++() { 
        this->m_A += 10;
        this->m_B += 10;
        return *this;
    }

    //返回值
    const Person3 operator++(int) { 
        Person3 temp = *this;
        this->m_A += 10;
        this->m_B += 10;
        return temp;
    }

private:
    int m_A;
    int m_B;
};


//运算符重载函数的重载
ostream& operator<<(ostream& cout, Person3& p1) {
    cout << "m_A = " << p1.m_A << "  m_b= " << p1.m_B;
    return cout;
}

void test02() {
    Person3 p1(10, 10);
    Person3 p2(50, 50);
    cout << p1 << endl;
    cout << ++(++p1) << endl;
    p2++;
    cout << p2 << endl;
    cout << p2++ << endl;
}


int main() {
    test02();

    return 0;
}
  • 写回答

1条回答 默认 最新

  • _GX_ 2022-01-14 17:46
    关注

    operator<<第二个参数改为const Person3&,因为后缀++返回的类型是const Person3,不能传递给Person3&类型

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 1月22日
  • 已采纳回答 1月14日
  • 创建了问题 1月14日

悬赏问题

  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000