首页 > 解决方案 > 多文件工厂方法

问题描述

有两个类BaseDerived基数.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 *'

这是为什么?我该如何解决这个错误?

标签: c++inheritancefactory-method

解决方案


你可以尝试这样做

// 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 即可打破这种依赖关系。如果您还需要在标头中引用它,您可以使用前向声明。


推荐阅读