关于c++运算符重载疑问

visual studio 2019版本,c++20

类文件

class Average {
    int sum;
    int n;

public:
    Average(int x=0,int y=0):sum(x),n(y) {};
    friend Average operator+(Average &avg1, Average &avg2);//重载加法
    friend std::ostream& operator<<(std::ostream &out,Average &avg);//重载输出符号<<
    Average(const Average& copy) :sum(copy.sum), n(copy.n) {
        cout << "调用赋值构造函数"<<endl;
    }
    Average operator+=(int x) {
        sum += x;
        n++;
        return *this;
    }
};

Average operator+(Average& avg1, Average& avg2) {
    return { avg1.sum + avg2.sum,avg1.n + avg2.n };//返回时自动初始化
}

std::ostream& operator<<(std::ostream& out, Average& avg) {
    out<< static_cast<float>(avg.sum) / static_cast<float>(avg.n);
    return out;
}

主函数


int main(int argc, char* argv[]) {
    Average avg{};

    avg += 4;
    std::cout << avg << '\n'; // 4 / 1 = 4

    avg += 8;
    std::cout << avg << '\n'; 

    avg += 24;
    std::cout << avg << '\n'; 

    avg += -10;
    std::cout << avg << '\n';

    (avg += 6) += 10; // 2 calls chained together
    std::cout << avg << '\n'; 

    Average copy{ avg };
    std::cout << copy << '\n';

    return 0;
}

运行结果

调用赋值构造函数
4
调用赋值构造函数
6
调用赋值构造函数
12
调用赋值构造函数
6.5
调用赋值构造函数
调用赋值构造函数
6.4(这里结果应该是7)
调用赋值构造函数
6.4

调试

调试时候发现连续两个+=号过程中没有出错,但是后面一个*this的值没有返回

img

img

后面两个为7

核心:代码其实走了默认生成的拷贝构造函数,由于都是基本类型 int 之类的数据,正常运行

如有帮助,望点击我回答右上角【采纳】按钮支持一下

你的代码里面,连续两次调用,第二次调用其实也变化了,只是变化的那个是临时变量,不是你的对象本身

改动如下,你返回 引用 即可确保每次改动对象本身

    Average& operator+=(int x)
    {
        sum += x;
        n++;
        return *this;
    }

img

#include <iostream>

using namespace std;

class Average {
    int sum;
    int n;

public:
    Average(int x = 0, int y = 0) :sum(x), n(y) {};

    friend Average operator+(Average& avg1, Average& avg2)
    {
        return { avg1.sum + avg2.sum,avg1.n + avg2.n };//返回时自动初始化
    }

    friend std::ostream& operator<<(std::ostream& out, Average& avg)
    {
        out << static_cast<float>(avg.sum) / static_cast<float>(avg.n);
        return out;
    }

    Average(const Average& copy) :sum(copy.sum), n(copy.n)
    {
        cout << "调用赋值构造函数" << endl;
    }

    Average& operator+=(int x)
    {
        sum += x;
        n++;
        return *this;
    }
};


int main(int argc, char* argv[]) 
{
    Average avg{};

    avg += 4;
    std::cout << avg << '\n'; // 4 / 1 = 4

    avg += 8;
    std::cout << avg << '\n';

    avg += 24;
    std::cout << avg << '\n';

    avg += -10;
    std::cout << avg << '\n';

    (avg += 6) += 10; // 2 calls chained together
    std::cout << avg << '\n';

    Average copy{ avg };
    std::cout << copy << '\n';

    return 0;
}