I have defined a struct in another file called file1.h (example) and when I declare an array using that struct in another file called File2.h, i get the error Message:
"Incomplete Type "array[]" is not allowed"
Example Code:
File1.h:
#ifndef MYSTRUCT_H
#define MYSTRUCT_H
struct MyStruct
{
float number1;
float number2;
};
#endif
File2.h:
#ifndef MY_CLASS_H
#define MY_CLASS_H
#include "File1.h"
class MyClass
{
public:
MyStruct array[]; // I get the error here
};
#endif
In C++, a member of a struct or class which is of an array type must be declared with a compile-time size.
(this is different in C which has a flexible array member - see here).
Therefore this will compile:
#include <cstddef> // for size_t
// ...
class MyClass {
public:
static constexpr size_t sz = 10; // compile time constant
MyStruct arr[sz];
};
However:
In C++ it is usually recommended to use std::vector
for dynamic size arrays, and std::array
for static size ones.
You seem to require the array to be of dynamic size, and therefore you should use std::vector
:
#include <vector>
// ...
class MyClass {
public:
std::vector<MyStruct> arr;
};
Here arr
can be dynamically resized whenever you need.
Note:
Your array
is not a very good name for a member. I renamed array
to arr
to avoid collision with std::array
.