RedPotato
RedPotato

Reputation: 7

how to use struct in a class

lifeform.h

class lifeform
{
  public:
    struct item;
    void buyItem(item &a);
   //code..
}; 

lifeform.cpp

struct lifeform::item
{
std::string type,name;
bool own;
int value,feature;

    item(std::string _type,std::string _name,int _value,int _feature):type(_type), name(_name),value(_value),feature(_feature)
     {
        own=false;
     }
};

lifeform::item lBoots("boots","Leather Boots",70,20);

void lifeform::buyItem(item &a)
{
if(a.own==0)
{

    inventory.push_back(a);
    a.own=1;
    addGold(-a.value);
    std::cout << "Added " << a.name << " to the inventory.";

    if(a.type=="boots")
    {
        hp-=inventory[1].feature;
        inventory[1]=a;
        std::cout << " ( HP + " << a.feature << " )\n";
        maxHp+=a.feature;
        hp+=a.feature;
    }
    }

there is no error so far but when i wanna use them in main.cpp like this

 #include "lifeform.h"
 int main()
 {
 lifeform p;
 p.buyItem(lBoots);
 }

compiler says me [Error] 'lBoots' was not declared in this scope but i declared it class am i missing something?

Upvotes: 1

Views: 66

Answers (1)

Pavel P
Pavel P

Reputation: 16940

To use your lifeform::item lBoots you need to declare it in main:

#include "lifeform.h"

extern lifeform::item lBoots; // <-- you need this.

int main()
{
    lifeform p;
    p.buyItem(lBoots);
}

Or alternatively you should place extern lifeform::item lBoots; in your lifeform.h.

Upvotes: 1

Related Questions