【问题标题】:C++ import loop with two classes?带有两个类的 C++ 导入循环?
【发布时间】:2011-12-01 22:01:50
【问题描述】:

我确定以前有人问过这个问题,但我似乎找不到。

我有两个班级,VectorPoint

文件是这样的(有点重复):

vector.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.cpppoint.h 看起来基本相同,只是在定义中将 vector 替换为 point

我将它们包括在内:

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

当我编译时,我得到这个错误:

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

我认为这个错误是说 Point 还没有被声明,但是当我通过导入 point.cppvector.h 内声明它时,我得到了一个 巨大 一堆错误.

谁能解释一下这个问题?

谢谢!


应用@ildjarn 的建议后,这些错误消失了,我只剩下一个:

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

还有一行:

Vector(Point const);

我在.cpp 文件中这样定义它:

Vector::Vector(Point const &point) {

【问题讨论】:

标签: c++ class import compiler-errors


【解决方案1】:
  1. 不应包含 .cpp 文件,而应包含 .h 文件。

  2. vector.cpp 需要#include "point.h" 并且(大概)point.cpp 需要#include "vector.h"

  3. 仅当您不执行任何需要类型大小或接口的操作时,前向声明才足够。因为Vector 的构造函数按值取Point,所以它的大小必须是已知的;将Vector 的构造函数更改为通过const 引用来获取Point,并且前向声明仍然足够。

  4. 您的标头需要#include guards(或#pragma once,如果您不介意不是100% 可移植的话)。

EDIT(响应 OP 的编辑):

您的声明和定义现在不匹配 - 即,您的定义是正确的,但您的声明需要 Point const&amp; 而不仅仅是 Point const

【讨论】:

  • 那个错误消失了,谢谢!现在出现了一个不那么神秘的问题(是的!!!)请再次查看我的问题。
  • 感谢您的回复,非常感谢您的意见。我试过了,但我似乎得到了相同的结果。
  • @Blender :那么请发布您更新代码的准确副本。请注意,前向声明仍然是必要的。
  • 我尝试将 & 符号放在这一行中几乎每个位置:Vector(Point const&amp;);
  • 我的代码太糟糕了,我只是根据您的建议从头开始重写了整个程序。感谢您的意见!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2021-12-20
  • 2016-05-12
  • 2021-08-12
  • 2015-07-13
  • 1970-01-01
相关资源
最近更新 更多