C++ 上的循环依赖和继承编译错误
Cyclic dependency and inheritance compilation error on c++
我在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()
{
}
相关文章:
- C++ 多级虚拟继承编译问题
- 编译时继承类中的隐式虚拟与显式虚拟
- 在编译时检查未实例化的类模板是否继承自其第一个模板参数
- 继承的构造函数,在 clang++3.9 中编译,在 g++ 7 中失败
- 使用多重继承时出现编译错误
- 为什么下面的代码不会编译(c++中的继承)
- 继承可以用来减少C++中编译代码的大小吗?
- C++ 上的循环依赖和继承编译错误
- 编译器无法编译继承 C++
- 如果对象是堆栈创建的(包括继承的类型),是否可以发出编译错误
- 获取多重继承中基类的编译时常量偏移量
- 可以用参数包编译C 17 lambda继承的编译器
- 为什么 Visual C++无法编译从私有嵌套类继承的友元模板
- C++中的继承和模板:为什么以下一段代码不编译?
- 继承结构的类型转换导致g++编译错误
- 继承受保护的函数和公共变量C++时发生多重继承编译错误
- 钻石继承方案在 G++ 中编译良好,但在 VC++/Eclipse 中产生警告/错误
- C++的多重继承和多重实现编译但崩溃
- 继承编译时或运行时
- 多重(菱形)继承编译而不"virtual",但不使用