Reputation: 533
I'm trying to declare a class object inside a header but I can't get it working. I currently have 2 header files and 2 cpp files that defines what each function does. The classes are called Heltal and Array, and both of them are in their own header file (heltal.h and array.h).
I'm trying to declare the Heltal class object inside the private part of the Array class, but whatever I do I can't find a way to declare it. I've tried including the heltal.h header to the array.h header but then it starts complaining about being redefined.
Declaring it in the array.cpp however works just fine but I would like to have it defined in the header instead.
Here's what the files look like at the moment:
heltal.h
class Heltal {
public:
Heltal();
Heltal(int tal);
~Heltal();
void set(int tal);
bool operator < (const Heltal &heltal) const
{
return (heltal < heltal.heltal);
}
bool operator > (const Heltal &heltal) const
{
return (heltal > heltal.heltal);
}
private:
int heltal;
};
array.h
#include <vector>
class Array {
public:
Array();
Array(int in);
~Array();
int Random(int min, int max);
private:
Heltal h;
int size;
};
Both headers are included in the main.cpp
Upvotes: 2
Views: 4835
Reputation: 290
When compile a c/cpp file, the included file would be expand in the c/cpp file first. and some class should be in a right order. e.g. Heltal MUST before Array, so your include order should ensure this.
Upvotes: 1
Reputation: 12044
You do need to include heltal.h inside array.h, but both files will need include guards:
#ifndef array_h_guard
#define array_h_guard
// contents of array.h go here
#endif // array_h_guard
and similarly for heltal.h. This will prevent the multiple inclusion.
Note that you could simply only include heltal.h from array.h, which also fixes the immediate issue, but the include guards are safer.
Upvotes: 0
Reputation: 726479
You started along the right path when you included Heltal.h
inside Array.h
.
Add the include guards to your headers, this will help you avoid duplicate inclusions:
#ifndef HELTAL_H
#define HELTAL_H
class Heltal {
...
};
#endif
Now you can safely include Heltal.h
at the top of Array.h
, and your problem will be solved.
Upvotes: 3