I'm having an issue compiling that code. I know the code dose nothing, but it gave me an error saying " use of undefined type Humans, how can I make it work? how can I make classes that can access other classes instances in cpp ? Thank you :)
#include <iostream>
class Humans;
class Animals
{
public:
Animals() :health(1)
{
}
int health;
void Attack(Humans a)
{
a.health = 10;
}
};
class Animals;
class Humans
{
public:
Humans() :health(0)
{
}
int health;
void Attack(Animals s)
{
s.health = 5;
}
};
int main()
{
Humans max;
Animals lion;
lion.Attack(max);
}
A forward declaration only states that a thing with a particular name exists somewhere; you can't use an instance of it for anything until the definition is also known.
Separate the class definitions and the member function definitions.
(This is the "default" way of writing C++, with class definitions and function definitions in separate files.)
class Human;
class Animal
{
public:
Animal();
// A forward declaration is enough since we don't
// try to use 'a' here.
void Attack(Human a);
int health;
};
class Human
{
public:
Human();
void Attack(Animal s);
int health;
};
Animal::Animal() : health(1) {}
void Animal::Attack(Human a)
{
a.health = 10;
}
Human::Human() : health(0) {}
void Human::Attack(Animal s)
{
s.health = 5;
}
(And don't use plural names for singular things. A lion is an animal, not an "animals".)