为什么我的重载“ +”运算符返回错误的总金额?

问题描述 投票:-1回答:1

因此,我试图解决运算符重载问题,并试图在main()中添加两个实例化框的长度和高度。问题是总数应该为myBox(2,4)+ myBox2(1,2)=(3,6),但是输出总数错误地显示为“ 2/3”。

#include<iostream>

using namespace std;

class Box {

    public:
        int length, height;
        Box(){ 
            length = 1, height = 1;
        }
        Box(int l , int h) {
            length = l, height = h;
        }
        Box operator +(const Box& boxToAdd) {
            Box boxSum;
            boxSum.length = boxSum.length + boxToAdd.length;
            boxSum.height = boxSum.height + boxToAdd.height;
            return boxSum;
        }
    };


    ostream& operator<<(ostream& os, const Box& box) {
    os << box.length << " / " << box.height << endl;
        return os;

    }
    int main() {
        Box myBox(2,4);
        cout << "First box length and height: "<<myBox << endl; // Outputs length and height data member values.
        Box myBox2(1, 2);
        cout << "Second box length and height: " << myBox2 << endl;

        cout << "The total of both boxes is: " << myBox + myBox2 << endl;
        cin.get();
}
c++ overloading operator-keyword
1个回答
1
投票

operator+中,您正在从boxSum中执行加法;刚才使用length = 1, height = 1;进行了默认构造,然后得到的结果为21 + 1)和32 + 1)。您应该从当前实例执行添加。例如

Box operator +(const Box& boxToAdd) {
    Box boxSum;
    boxSum.length = this->length + boxToAdd.length;
    boxSum.height = this->height + boxToAdd.height;
    return boxSum;
}

LIVE

© www.soinside.com 2019 - 2024. All rights reserved.