• 重载运算符 +


    任务描述: 

    定义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
  • 相关阅读:
    IK 用java 代码实现分词
    杭电2017
    线性表学习
    一个比较有意思的C语言问题
    杭电1020
    python注释
    Java API —— 递归
    Java API —— File类
    Java API —— 异常
    Map集合案例
  • 原文地址:https://www.cnblogs.com/junfblog/p/12803279.html
Copyright © 2020-2023  润新知