重载运算符 +

任务描述: 

定义Boat与Car两个类,二者都有weight属性,定义重载运算符 +,计算二者的重量和。

源代码:

#include <stdio.h>
#include <iostream>
using namespace std;
class Boat
{
public:
    Boat(){}
    Boat(int Boat_weight)
    {
        this->Boat_weight=Boat_weight;
    }

    int getwei()
    {
        return this->Boat_weight;
    }

    void show()
    {
        cout<<"船的重量为"<<this->Boat_weight<<"t"<<endl;
    }

private:
    int Boat_weight;
};

class Car
{
public:
    Car(){
        car_weight=0;
    }
    Car(int car_weight)
    {
        this->car_weight=car_weight;
    }
        
    void show()
    {
        cout<<"汽车的重量为"<<this->car_weight<<"t"<<endl;
    }

    int getwei()
    {
        return this->car_weight;
    }

    Car operator+ (Boat& b) {
        Car c;
        c.car_weight = this->car_weight + b.getwei();
        return c;
    }


    
private:
    int car_weight;

};


int main()
{
    
    // 请在此添加代码
    /********** Begin *********/
    int boat_wei,car_wei;
    cin>>boat_wei>>car_wei;
    Boat boat(boat_wei);
    Car car(car_wei);
    boat.show();
    car.show();
    
    Car c;
    c = boat_wei + car_wei;
    cout << "总重量为" <<c.getwei()<<"t"<<  endl;

    
    
    /********** End **********/
    return 0;
}

输入:

10 1

输出:

船的重量为10t
汽车的重量为1t
总重量为11t

猜你喜欢

转载自www.cnblogs.com/junfblog/p/12803279.html