栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【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 
using namespace std;
#include 
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;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/862166.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号