Home > front end >  Having trouble with class in c
Having trouble with class in c

Time:12-27

I'm obviously making a mistake here, but please help me.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    class Item
    {
       int Value;
       int Use_On(Entity Target)
       {
            Target.HP  = Value;
        }
    };

    class Entity
    {
        int HP;
        Item Slot;
    };
}

The Item class have a function that change the HP value of an Entity object, and the Entity class have an Item object. This result in an error because Entity wasn't declared yet. I've tried to make a prototype of the Entity class and declare it before the Item class, but this just result in another error saying Entity is an incomplete type. How can I solve this? Also, sorry for the title, I'm not really good at english :|

CodePudding user response:

The solution is to forward-declare the class, declare the class method first, and define it only after all classes have been declared.

class Entity;

class Item
{
    int Value;
    int Use_On(Entity Target);
};

class Entity
{
    int HP;
    Item Slot;
};

int Item::Use_On(Entity Target)
{
    Target.HP  = Value;
}

See your C textbook for a complete discussion and explanation of forward reference, and the details of the alternative ways to declare and define class methods.

This should solve the immediate compilation error, but there are multiple other problems with the shown code that you will need to fix.

  1. Use_On is declared as returning an int, but does not return anything.

  2. In C parameters get passed by value by default, which means that Use_On ends up modifying only its local parameter, and otherwise accomplishing absolutely nothing, whatsoever. Whatever object gets passed into this class method remains completely unchanged. You will need to change the code to pass the parameter either via a pointer or by reference. Your C textbook will also have a discussion on these topics.

  3. Classes should be declared in global scope, instead of inside functions like main(), where some class features are not available.

  • Related