another incomplete type Error C++ [duplicate]
-
13-07-2021 - |
Question
Possible Duplicate:
Circular Dependencies / Incomplete Types
writing a litte c++ program and be confused....
got 4 classes, 2 important for this error...
got the error message "field 'dot' has incomplete type" in Line 13 and "expected ';' befor '(' token" in same Line
The Error seems to start in the Vector3.cpp, where only the include of the Vector3.h and the empty methodes
deleted the include "Vector3.h" in the Normal3 Header, thought will be running in a circle... not so well...
some ideas? hope so :) and ty for answers
Here are my two important classes:
#ifndef NORMAL3_H
#define NORMAL3_H
class Normal3 {
public:
double x, y, z;
Normal3 mul(Normal3 n);
Normal3 add(Normal3 n);
Normal3 dot(Vector3 v); //Line 13
Normal3(double x = 0, double y = 0, double z = 0)
: x(x), y(y), z(z)
{ }
};
#endif //NORMAL3_H
AAAAAAAAAAAAAAAAAAAAAND
#ifndef VECTOR3_H
#define VECTOR3_H
#include "Normal3.h"
class Vector3 {
public:
double x, y, z, magnitude;
Vector3 add(Vector3 v);
Vector3 add(Normal3 n);
Vector3 sub(Normal3 n);
Vector3 mul(double c);
double dot(Vector3 c);
double dot(Normal3 n);
Vector3 normalized();
Normal3 asNormal();
Vector3 refelctedOn(Normal3 n);
Vector3(double x = 0, double y = 0, double z = 0, double m = 0)
: x(x), y(y), z(z), magnitude(m)
{ }
};
#endif //VECTOR3_H
Solution
It just means that the compiler does not know what Vector3
is at that point. If you declare it in advance, the error will disappear:
#ifndef NORMAL3_H
#define NORMAL3_H
class Vector3; // Add this line
class Normal3 {
// ...
};
UPDATE: As john says in his comment, it would be a good improvement to replace #include "Normal3.h"
in Vector3.h with just another forward declaration, class Normal3;
:
#ifndef VECTOR3_H
#define VECTOR3_H
class Normal3; // instead of #include "Normal3.h"
class Vector3 {
// ...
};
You should try to keep #include
directives in your headers to a minimum in order to avoid excessive compilation dependencies. You only need to include a header if it defines a type you are using (usually because a class you are defining has a data member of this type). If you are only using pointers or references to that type or function parameters of that type (as in your example), a forward declaration is enough.
OTHER TIPS
your file normal3.h
nothing know about Vector3
.
I see that Vector3 v
does not changes into dot
, then you should write:
instead Normal3 dot(Vector3 v); //Line 13
as
#ifndef NORMAL3_H
#define NORMAL3_H
class Vector3;
class Normal3 {
public:
double x, y, z;
Normal3 mul(Normal3 n);
Normal3 add(Normal3 n);
Normal3 dot(const Vector3 &v); //Line 13
Normal3(double x = 0, double y = 0, double z = 0)
: x(x), y(y), z(z)
{ }
};
#endif //NORMAL3_H