头文件的多次包含

时间:2019-07-18 07:54:40

标签: c++ header multiple-inclusions

我有三个文件:Factory.hpp,Factory.cpp和Operand.hpp。在 Operand.hpp 中有一个模板类,在我的 Factory文件中有一个以指定的正确类型创建创建操作数的工厂。问题是,在特殊情况下,我需要在Operand类中调用工厂的主函数来重新创建Operand,但是由于我的 Factory,我无法在Operand中包含 Factory.hpp .hpp 已包含Operand.hpp。

现在我只是将Operand类放在工厂文件中,但这不是一个好习惯……

Operand.hpp


#include "Factory/Factory.hpp"

template <typename T>
class Operand : public IOperand {
        public:
                Operand(const eOperandType &type, const std::string &value);
                ~Operand();
                std::string toString() const;
                eOperandType getType() const;
                IOperand *operator+(const IOperand &rhs) const;
                IOperand *operator-(const IOperand &rhs) const;
                IOperand *operator*(const IOperand &rhs) const;
                IOperand *operator/(const IOperand &rhs) const;
                IOperand *operator%(const IOperand &rhs) const;
        private:
                const eOperandType _type;
                T _value;
};

Factory.hpp


#include <map>
#include "IOperand.hpp"
#include "Operand/Operand.hpp"
#include <istream>
#include <iostream>
#include <sstream>
#include <limits>
#include "IOperand.hpp"
#include "Exception/Exception.hpp"


class Factory {
    public:
        Factory();
        ~Factory();
        static IOperand *createOperand(eOperandType type, const std::string &value);
    private:
    typedef std::map<eOperandType, IOperand *(Factory::*)(
        const std::string &value)> operands_t;
        static operands_t _operands;
        IOperand *createInt8(const std::string &value);
        IOperand *createInt16(const std::string &value);
        IOperand *createInt32(const std::string &value);
        IOperand *createFloat(const std::string &value);
        IOperand *createDouble(const std::string &value);
        IOperand *createBigDecimal(const std::string &value);
};


解决方案

最简单的解决方案是在 Operand.hpp 中删除factory的包含,并在 Operand.hpp 的开头添加如下工厂类的原型:

class Factory;

template <typename T>
class Operand : public IOperand {
        public:
                Operand(const eOperandType &type, const std::string &value);
                ~Operand();
                std::string toString() const;
                eOperandType getType() const;
                IOperand *operator+(const IOperand &rhs) const;
                IOperand *operator-(const IOperand &rhs) const;
                IOperand *operator*(const IOperand &rhs) const;
                IOperand *operator/(const IOperand &rhs) const;
                IOperand *operator%(const IOperand &rhs) const;
        private:
                const eOperandType _type;
                T _value;
};

0 个答案:

没有答案