C++ 運算子過載

zsdeus133發表於2018-07-31

運算子過載的一個例子

#include <iostream>
using namespace std;


class Box {
public:
    int length;
    int breadth;
    int height;

    Box operator + (const Box& b) {
        Box box;
        box.length = b.length + this->length;
        box.breadth = b.breadth + this->breadth;
        box.height = b.height + this->height;
        return box;
    }
};

void main()
{
    Box box1;
    box1.length = 1;
    box1.breadth = 2;
    box1.height = 3;

    Box box2;
    box2.length = 1;
    box2.breadth = 2;
    box2.height = 3;

    Box box = box1 + box2;
    cout << box.length << " " << box.breadth << " " << box.height << endl;
    system("pause");
}

相關文章