Code:
#include <iostream>#include <string>
class Item
{
public:
Item(const std::string& name, float cost, float value, float weight)
: name(name), cost(cost), value(value), weight(weight)
{}
std::string Name() const { return name; }
float Cost() const { return cost; }
float Value() const { return value; }
float Weight() const { return weight; }
friend std::ostream& operator<<(std::ostream& os, const Item& item)
{
os << "Name: " << item.name << std::endl;
os << "Cost: " << item.cost << std::endl;
os << "Value: " << item.value << std::endl;
os << "Weight: " << item.weight << std::endl;
return os;
}
protected: //!! can be accessed directly by derived classes
std::string name{ "Generic Item" };
float cost{ 2 };
float value{ 1 };
float weight{ 1 };
};
class Weapon : public Item
{
public:
Weapon(const std::string& name, float cost, float value, float weight, float attackPower, float durability)
: Item{ name, cost, value, weight }, attackPower(attackPower), durability(durability)
{}
friend std::ostream& operator<<(std::ostream& os, const Weapon& weapon)
{
os << static_cast<const Item&>(weapon);
os << "Attack Power: " << weapon.attackPower << std::endl;
os << "Durability: " << weapon.durability << std::endl;
return os;
}
float AttackPower() const { return attackPower; }
float Durability() const { return durability; }
private:
float attackPower{ 5 };
float durability{ 1 };
};
class Sword : public Weapon
{
public:
Sword(const std::string& name, float cost, float value, float weight, float attackPower, float durability)
: Weapon{ name, cost, value, weight, attackPower, durability }
{}
};
class Bow : public Weapon
{
public:
Bow(const std::string& name, float cost, float value, float weight, float attackPower, float durability, float range)
: Weapon{ name, cost, value, weight, attackPower, durability }, range(range)
{}
float Range() const { return range; }
friend std::ostream& operator<<(std::ostream& os, const Bow& bow)
{
os << static_cast<const Weapon&>(bow);
os << "Range: " << bow.range << std::endl;
return os;
}
private:
float range{ 1 };
};
int main() {
Sword Greatsword{ "Greatsword", 1000, 800, 15, 34, 100 };
Sword BastardSword{ "Bastard Sword", 1300, 1000, 25, 50, 100 };
std::cout << Greatsword << std::endl;
std::cout << BastardSword << std::endl;
Bow Greatbow{ "Great Bow", 600, 300, 4, 60, 100, 600};
std::cout << Greatbow << std::endl;
}