C++ 上的循环依赖和继承编译错误

Cyclic dependency and inheritance compilation error on c++

本文关键字:继承 编译 错误 依赖 循环 C++      更新时间:2023-10-16

我在C++中遇到了一个涉及循环依赖和继承的问题。

我已经部分实现了设计,我将使用pesudocode来说明问题发生的位置。

第一部分是:

//app.h
include rel.h
class Rel; // forward declaration
class App {
shared_ptr<Rel> //member variable
}
//rel.h
include app.h
class App; //forward declaration
class Rel {
shared_ptr<App> //member variable
}

直到这里,程序编译时没有警告

然后,我想添加继承,如下所示:

//app.h
include rel.h
include drel.h
class Rel; // forward declaration
class DRel // forward declaration
class App {
shared_ptr<Rel> //member variable
shared_ptr<DRel> //member variable
}
//rel.h (the same as before)
include app.h
class App; //forward declaration
class Rel {
shared_ptr<App> //member variable
}
//drel.h
include app.h
include rel.h
class App; //forward declaration
class DRel: Rel { // compile error here: expected class name before { token
shared_ptr<App> //member variable
}

如您所见,编译器抛出"{ token之前的预期类名",这意味着Rel没有解析,但是为什么没有继承的第一个代码有效而第二个代码不起作用?我该如何解决这个问题?这是一种"错误"的模式吗?

我正在使用 c++14

我知道有很多关于我遇到的问题的问题,但我找不到我具体问题的答案。也许我看不到它...

由于您声明的所有变量都不需要知道 App、Rel 和 DRel 占用的空间,因此您甚至不需要#include有问题的标头,您只需像您一样转发声明名称即可。

所以你有你.h

class A;
class B;
class C {
std::shared_ptr<A> ptra;
std::shared_ptr<B> ptrb;
};

然后你的.cpp

#include "A"
#include "B"
C::C()  { ... }

原始头文件需要由 #ifdefs 保护,如下所示:

#ifndef CYCLIC_DEPENDECY_1
#define CYCLIC_DEPENDECY_1
#include "cyclic_dependency2.h"
class Rel; // forward declaration
class App {
std::shared_ptr<Rel> test; //member variable
};
#endif


#ifndef CYCLIC_DEPENDECY_2
#define CYCLIC_DEPENDECY_2
#include "cyclic_dependency1.h"
class App; //forward declaration
class Rel {
std::shared_ptr<App> test;//member variable
};
#endif

#include <iostream>
#include <memory>
#include "cyclic_dependency2.h"
class Rel; // forward declaration
class DRel; // forward declaration
class DRel: Rel { 
std::shared_ptr<App> test ;//member variable
};
main()
{
}