lundi 15 mai 2023

Composite Design Pattern Inheritance [duplicate]

I wrote an inventory system to learn the composite design pattern. I apologize for the format this is my first post.

#pragma once
class InventoryManager
{
public:
    virtual int ReturnInventoryCostTotal() { return 0; };
    virtual void AddItem(InventoryManager a) {};
    virtual void RemoveItem() {};
};
////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "InventoryManager.h"
#include <vector>
class Shelf : public InventoryManager
{
public:
    std::vector<InventoryManager> inventory;
    int ReturnInventoryCostTotal()override;
    void AddItem(InventoryManager a)override;
    void  RemoveItem()override;
};
//////////////////////////////////////////////////////////////////////////////////////
#include "shelf.h"
#include <iostream>
int Shelf::ReturnInventoryCostTotal()
{
    int numberOfItemsInInventory = inventory.size();
    int total = 0 ;
    for (int i = 0; i < numberOfItemsInInventory; i++)
    {
        total = total + inventory[i].ReturnInventoryCostTotal();
    }
    std::cout << total << std::endl;
    return total;
}

void Shelf::AddItem(InventoryManager a)
{
    inventory.push_back(a);
}

void Shelf::RemoveItem()
{
}
/////////////////////////////////////////////////////////////////////////
#pragma once
#include "InventoryManager.h"
class Item : public InventoryManager
{
public:
 int cost;
 Item(int cdst) { cost = cdst; };
 int ReturnInventoryCostTotal()override;
 void AddItem(InventoryManager a)override;
 void RemoveItem()override;
};

#include "Item.h"
int Item::ReturnInventoryCostTotal()
{
    return cost;
}

I am trying to call the Item classes ReturnInventoryCostFunction but I keep calling the base Class function. The goal is to be able to get the total of all the items on a shelf. I dont think including the main() is necessary I know I am adding the items to the shelf correctly and have verified that the Shelf.ReturnInventoryCostFunction IS calling the base class InventoryManagers function instead of item to get the cost.

Aucun commentaire:

Enregistrer un commentaire