c++ - 带有继承构造函数的静态变量
问题描述
我有一个名为的抽象类Shoes
和两个派生类Sandals
,Sports
我创建了它们。该程序就像一个小商店,用静态变量计算商店里有多少鞋子,如果超过 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;
}
解决方案
推荐阅读
- javascript - 尽管为 keydown(或 keyup)函数使用了数组,但我的代码仍然拒绝让我在跳跃时移动
- html - CSS网格响应子元素垂直和水平居中项目
- c - 使用指针数组递归时的 C SegFault
- windows - 用于提取与特定事件 ID 关联的登录类型的 PS 命令
- java - 解决 android.content.res.Resources 错误的问题
- fn - Fn 函数在超时前终止
- python-3.x - Python 异常没有详细信息
- javascript - 使用 selenium web 驱动程序在地图中的特定位置执行右键单击
- java - 如何在Android中实现侧板
- ssl - SSL/TLS 证书管理(密钥、crt 和 pem)