【c++】设计一个武器类

pta的一道题

武器类的设计

请设计一个枪支类Gun, 每把枪都有名称,重量,射程,弹匣大小,已装子弹数等属性,有扣动扳机、装子弹和打印枪支信息的行为,每扣动一次扳机,射出一发子弹,装子弹时,可以一次装入多发子弹但不能超过弹匣大小,打印会输出枪的所有属性信息。根据给定的main函数,完成类的设计。注意:程序代码要包含下面的main函数,不得改动。  

int main(){
    Gun g1;
    g1.printInfo();
    string name;
    int weight,range,capacity,bullet;
    getline(cin,name);
    cin>>weight>>range>>capacity>>bullet;
    Gun g2(name,weight,range,capacity,bullet);
    int num;
    cin>>num;
    if(g2.getBullet()+num<=g2.getCapacity())
       g2.load(num);
    g2.pull_trigger();
    g2.printInfo();
    return 0;
}

输入格式:

输入包含三行数据。第一行是一把枪的名字。第二行包含4个整数,中间用空格分隔,分别表示枪的重量,射程,弹匣容量和装的子弹数。第三行是一个整数,代表装子弹数。

输出格式:

输出包含两行,分别是两把枪的信息,用回车分隔。

注意:枪的名字的输出宽度为15,重量的输出宽度为4,射程的输出宽度为3,弹匣容量的输出宽度为2。

输入样例:

在这里给出一组输入。例如:

HK USP
720 50 15 0
10

输出样例:

在这里给出相应的输出。例如:

  Mauser pistol:weight:1000,range: 25,Magazine capacity:10,the number of bullets:0
         HK USP:weight: 720,range: 50,Magazine capacity:15,the number of bullets:9
#include <bits/stdc++.h>
using namespace std;
#include <utility>
class Gun {
private:
    int weight, range, capacity, bullet;
    std::string name;
public:
    Gun(std::string name, int weight, int range, int capacity, int bullet): name(std::move(name)),
    weight(weight), range(range), capacity(capacity), bullet(bullet){}
    Gun(): Gun("Mauser pistol", 1000, 25, 10, 0){}
    void printInfo() {
        std::cout << std::setw(15) << name << ":weight:" << std::setw(4) << weight << ",range:"
        << std::setw(3) << range << ",Magazine capacity:" << std::setw(2) << capacity << ",the number of bullets:"
        << bullet<< std::endl;
    }
    int getBullet() const {
        return this->bullet;
    }
    int getCapacity() const {
        return this->capacity;
    }
    void load(int num) {
        if (num > capacity) {
            bullet = capacity;
        } else {
            bullet = num;
        }
    }
    void pull_trigger() {
        if (bullet) bullet--;
    }
};
int main(){
    Gun g1;
    g1.printInfo();
    string name;
    int weight,range,capacity,bullet;
    getline(cin,name);
    cin>>weight>>range>>capacity>>bullet;
    Gun g2(name,weight,range,capacity,bullet);
    int num;
    cin>>num;
    if(g2.getBullet()+num<=g2.getCapacity())
        g2.load(num);
    g2.pull_trigger();
    g2.printInfo();
    return 0;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值