首页 > 解决方案 > 带有继承构造函数的静态变量

问题描述

我有一个名为的抽象类Shoes和两个派生类SandalsSports我创建了它们。该程序就像一个小商店,用静态变量计算商店里有多少鞋子,如果超过 50 则Sandals降价Sports。我必须在Shoes不添加新函数或变量的情况下保持类完好无损。我尝试这样做,但由于功能salePrice和它集成在鞋子的构造函数中,我很难做到这一点。
你能帮我更正代码吗?

鞋类

#pragma once
#include <iostream>
#include <vector>
using namespace std;

class Shoes
{
protected:
    int code;
    float price;
public:
    Shoes(int c, float p);
    virtual float salePrice() = 0;
    static int countShoes;
    static float totalPayment;
};
Shoes::Shoes(int c, float p)
{
    this->code = c;
    this->price = p;
}
int Shoes::countShoes = 0;
float Shoes::totalPayment = 0;

class Sandals : public Shoes
{
public:
    Sandals(int c, float p): Shoes(c,salePrice()) {};
    float salePrice()
    {
        if (Shoes::countShoes > 50)
        {
            price = price - (price * 30 / 100);
            totalPayment += price;
            return price;
        }
        else
        {
            totalPayment += this->price;
            return price;
        }
    }

};
class Sports :public Shoes
{
public:
    Sports(int c, float p) : Shoes(c, salePrice()) {};
    float salePrice()
    {
        if (Shoes::countShoes > 50)
        {
            price = price - (price * 10 / 100);
            totalPayment += price;
            return price;
        }
        else
        {
            totalPayment += this->price;
            return price;
        }
    }
};

主要的

#include <iostream>
#include <vector>
#include "Shoes.h"
using namespace std;

int main()
{
    vector<Shoes*> vshoes;
    float ShoppingCart = 0;

    int code;
    float price;
    int choice;
    cout << "Enter 1 for sandals, 2 for sports, 0 to stop shopping" << endl;
    cin >> choice;

    while (choice != 0)
    {
        cout << "Enter a code and price" << endl;
        cin >> code >> price;
        switch (choice)
        {
        case 1:
                vshoes.push_back(new Sandals(code, price));
            break;
        case 2:
            vshoes.push_back(new Sports(code, price));
            break;
        default:
            cout << "Invalid choice" << endl;
            break;
        }
        ShoppingCart += Shoes::totalPayment;
            cout << "Enter 1 for sandals, 2 for sports, 0 to stop shopping" << endl;
        cin >> choice;
    }
    cout << "You have purchased shoe in " << ShoppingCart << " dollars" << endl;
    return 0;
}

标签: c++classpointersinheritancestatic

解决方案


推荐阅读