开发者

C++ import loop with two classes?

I'm sure this question has been asked before, but I can't seem to find it.

I have two classes, Vector and Point.

The files are as such (a bit repetitive):

vec开发者_如何学运维tor.h:

#include <math.h>
#include <stdlib.h>

class Vector {
  friend class Point;

  public:
    ...

    Vector(Point); // Line 16

vector.cpp:

#include <math.h>
#include <stdlib.h>

#include "vector.h"

...

Vector::Vector(Point point) { // Line 29
  x = point.x;
  y = point.y;
  z = point.z;
}

point.cpp and point.h look mostly the same, except you swap vector with point in the definitions.

I include them as such:

#include "structures/vector.cpp"
#include "structures/point.cpp"

When I compile, I get this error:

structures/vector.h:16:17: error: field ‘Point’ has incomplete type
structures/vector.cpp:29:15: error: expected constructor, destructor, or type conversion before ‘(’ token

I think this error is saying that Point hasn't been declared yet, but when I declare it inside of vector.h by importing point.cpp, I get a huge pile of errors.

Could anyone shed some light on this problem?

Thank you!


Upon applying @ildjarn's suggestions, those errors went away and I am left with this single one:

structures/vector.h:16:18: error: expected ‘)’ before ‘const’

And the line:

Vector(Point const);

I define it like so in the .cpp file:

Vector::Vector(Point const &point) {


  1. You shouldn't be including .cpp files, you should be including the .h files.

  2. vector.cpp needs #include "point.h" and (presumably) point.cpp needs #include "vector.h".

  3. A forward declaration is only sufficient if you're not doing anything that requires the type's size or interface. Because Vector's constructor is taking a Point by value, its size must be known; change Vector's constructor to take the Point by const reference instead and a forward declaration will remain sufficient.

  4. Your headers need #include guards (or #pragma once if you don't mind not being 100% portable).

EDIT (in response to OP's edit):

Your declaration and definitions now mismatch -- i.e., your definition is correct but your declaration needs Point const& rather than just Point const.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜