c++ - 多文件工厂方法
问题描述
有两个类Base和Derived。 基数.h:
class Base {
public:
Base* create_obj();
};
和Base.cpp:
#include "Base.h"
Base* Base::create_obj() {
return new Derived();
};
和Derived.h:
#inlcude "Base.h"
class Derived : public Base {
};
如果两个类都在,main.cpp
那么就不会有错误。但是当我把它们放在上面的多个文件中时,我得到了这个错误:
Cannot initialize return object of type 'Base *' with an rvalue of type 'Derived *'
这是为什么?我该如何解决这个错误?
解决方案
你可以尝试这样做
// Base.h
class Base {
public:
Base* create_obj();
};
// Base.cpp
#include "Base.h"
#include "Derived.h"
Base* Base::create_obj() {
return new Derived();
};
// Derive.h
class Derived : public Base {
};
基本上我从“Base.h”中删除了“Derive.h”并将其移至“Base.cpp”。由于您没有在标题中派生,因此没有真正需要它。
这称为循环依赖,其中您有一个头文件试图包含另一个文件,但它本身需要包含在该头文件中。
在您的情况下,只需使用 .cpp 文件中的标头而不是 .h 即可打破这种依赖关系。如果您还需要在标头中引用它,您可以使用前向声明。
推荐阅读
- java - 无法为 Spring CryptoFactoryBean 设置 Crypto Provider
- java - 使用 VS Code 编译 Java,得到“对所需库的限制”错误消息
- reactjs - 有没有办法使用
作为我的过渡组件,同时使用 组件来显示菜单 onHover? - algorithm - 我可以在线性时间内检查有界列表是否包含重复项吗?
- python - 如何按数字分解pdf文本
- apache - Symfony 4 - 我的 Wampserver Vhost 不工作
- sql - 尝试从这两个查询中进行一个查询
- c# - C# 和 Python 文件创建带有库的设置文件
- python - 如何在 python 中加载 .mat 文件?
- amazon-web-services - 在控制台中创建 AWS 实例的备份和还原时遇到问题