gpt4 book ai didi

C++ - 构建顺序和依赖问题

转载 作者:太空宇宙 更新时间:2023-11-04 12:16:47 24 4
gpt4 key购买 nike

我似乎误解了一些与 C++ 中构建顺序相关的内容。所以我有这段代码,它定义了一个我用作 functionoid 的类(其目的是代替传递函数指针的对象):

#include "Imports.h"

class X: public Y
{
public:

X (T* t) { this->t= t; }
virtual ~X(){}

virtual void draw()
{
if (t->booleanReturningFunction())
{
t->someField.draw();
}
}

T* t;
};

我收到一个编译器错误,在我使用 T 的行号处提示“使用未定义类型 T”。但是,Imports.h 看起来像:

//The goal of this file is to have all the typcally needed imports in one place.

#if !defined(IMPORTS_H)
#define IMPORTS_H

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <assert.h>
#include <cmath>
#include <fstream>

class T;
class X;
class Y;

#include "Y.h"
#include "X.h"
#include "T.h"

#endif // if !defined(IMPORTS_H)

每个“.h”文件都包含该类的定义。现在 T 实际上确实有一个 X 对象(不是指针,而是一个 X 对象)。但是,据我所知,构建顺序中没有循环依赖,因为 X 只有一个指向 T 的指针,对吗?有什么我遗漏的,你可以从这段代码中看到吗?非常感谢您的帮助!

编辑:我解决了我的问题。问题是我在头文件中执行上述代码。可以理解,编译器无法基于前向引用编译 t->booleanReturningFunction()(它需要查看类声明才能知道将函数调用绑定(bind)到哪个地址)。

最佳答案

Now T actually does have an X object in it (not a pointer, but an X object).

给定这个顺序-

class T;
class X;
class Y;

#include "Y.h"
#include "T.h" // 1
#include "X.h"

T.h 如您所述,有一个 X 对象。直到此时 (1) 编译器不知道类 X 的定义。对于要实例化的对象,编译器应该看到完整的类定义,而不是 X 的前向声明。但是编译器提示未定义类型 T 似乎很奇怪。

关于C++ - 构建顺序和依赖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7356242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com