【问题标题】:C++ Circular Declaration IssuesC++ 循环声明问题
【发布时间】:2017-11-01 04:53:18
【问题描述】:

我遇到了循环声明的问题,但到目前为止找到的所有解决方案都不能直接解决问题。

这里有一些代码:

Transformable.h

#pragma once

#include "TransformMatrix.h"

class Transformable {
public:
    TransformMatrix Transform;
    virtual void transform_callback();
};

TransformMatrix.h

#pragma once

#include "Transformable.h"

class Transformable;

class TransformMatrix {

private:

    Transformable *callback_object;

public:

    TransformMatrix();

    TransformMatrix(Transformable *cb_object);

Transforms.h

#pragma once
#include "Transformable.h"
#include "TransformMatrix.h"

啊.h

class A: public Transformable {
public:
    A();

    /* We want a callback */
    TransformMatrix Transform = TransformMatrix(this);

我有一个实现基类的类,并使用一个特殊的头文件,所以我不必每次都包含两个文件。但我得到的错误是:

Transformable.h(7):错误 C3646:“转换”:未知覆盖
Transformable.h(7):错误 C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持 default-int。

【问题讨论】:

  • 您应该从 TransformMatrix.h 文件中删除 #include "Transformable.h" 指令。
  • 我也试过了,我最终得到:1>TransformMatrix.cpp(141): error C2027: use of undefined type 'Transformable' 1>TransformMatrix.h(8): note: see declaration of 'Transformable' 1>TransformMatrix.cpp(141): error C2227: left of '->transform_callback' must point to class/struct/union/generic type
  • 听起来您现在需要将#include "Transformable.h" 添加到您的 TransformMatrix.cpp 文件中?
  • 在 TransformMatrix.cpp 中添加 #include "Transformable.h"
  • 好吧,修复了它,但我还必须将 Transformable.h 中的虚拟 void 更改为常规 void,因为即使我使用类型转换,编译器也不知道cast 尚未实施。谢谢!

标签: c++ forward-declaration


【解决方案1】:

假设 TransformMatrix.h 可以将 Transformable 视为不透明类型,那么您可以简单地使用现有的前向声明,并从 TransformMatrix.h 中删除 #include Transformable.h时间>。 TransformMatrix 的实现文件可能需要添加 #include Transformable.h。 (这是从您问题下方的 cmets 收集的。)

但是,可能需要此类知识。然后,我们认为您的类依赖项中存在设计缺陷,并尝试对其进行更正。

我们注意到Transformable 有一个虚方法,但还想包含一个TransformMatrix。很可能,我们可以通过删除此依赖项来纠正您的问题。在这一点上,这只是猜测,因为您没有显示足够的代码来完全理解您的预期设计。

但是,如果我要尽可能地保持现有设计,我会将TransformMatrix 转换为模板,并将Transformable 抽象为模板参数。

#pragma once

template <typename T>
class TransformMatrixTemplate {
private:

    T *callback_object;

public:

    TransformMatrixTemplate();

    TransformMatrixTemplate(T *cb_object);

然后,typedefTransforms.h 中使用 Transformable 的模板。

#pragma once
#include "Transformable.h"
#include "TransformMatrix.h"

typedef TransformMatrixTemplate<Transformable> TransformMatrix;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-18
    • 2021-12-03
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多