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

【c++】设计一个武器类,第1张

pta的一道题

武器类的设计

请设计一个q支类Gun, 每把q都有名称,重量,射程,d匣大小,已装子d数等属性,有扣动扳机、装子d和打印q支信息的行为,每扣动一次扳机,射出一发子d,装子d时,可以一次装入多发子d但不能超过d匣大小,打印会输出q的所有属性信息。根据给定的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;
}

输入格式:

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

输出格式:

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

注意:q的名字的输出宽度为15,重量的输出宽度为4,射程的输出宽度为3,d匣容量的输出宽度为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;
}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/798909.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存