循环依赖混淆

时间:2014-10-15 13:38:56

标签: c++

我在c ++论坛中阅读了关于标题的Disch文章 http://www.cplusplus.com/forum/articles/10627/

我这里的代码有点令人困惑

ResourceHolder.h

using namespace std;
template<typename Resource, typename Identifier>
class ResourceHolder{
public:
    void load(Identifier id, const std::string &filename);

    template<typename Parameter>
    void load(Identifier id, const std::string &filename, const Parameter &secondParam);

    Resource &get(Identifier id);
    const Resource &get(Identifier id) const;
private:
    void    insertResource(Identifier id, std::unique_ptr<Resource> resource);


private:
    std::map<Identifier, std::unique_ptr<Resource>> mResourceMap;

};

ResourceIdentifier.h

// Forward declaration of SFML classes
namespace sf
{
    class Texture;
}

namespace Textures
{
    enum  ID
    {
        Eagle,
        Raptor,
        Desert,
    };
}

// Forward declaration and a few type definitions
template <typename Resource, typename Identifier>
class ResourceHolder;

typedef ResourceHolder<sf::Texture, Textures::ID> TextureHolder;

Aircraft.h

#pragma once
#include "Entity.h"
#include "ResourceIdentifiers.h"

class Aircraft : public Entity
{
public:
    enum  Type{
        Eagle,
        Raptor
    };


    Aircraft(Type type, const TextureHolder& textures);

private:
    virtual void drawCurrent(sf::RenderTarget &target, sf::RenderStates states) const;

private:
    Type mType;
    sf::Sprite mSprite;
};

我认为这是基于我读过的文章以正确的方式和错误的方式。

Aircraft.h

包括

ResourceIdentifier.h

包含

的前向声明
ResourceHolder.h

在文章中说明如果要转发声明,则需要使用指向类的引用或引用类。

在我的代码中,他们使用前向声明但从不使用指向类的指针。它实际上是一个模板类

当我在我的Aircraft.cpp上出现关于不兼容类型

的错误时

Aircraft.cpp

#include "Aircraft.h"

        #include "ResourceHolder.h" // --------- I got an error if this is not included.

    Textures::ID toTextureID(Aircraft::Type type){
        switch (type)
        {
        case Aircraft::Type::Eagle:
            return Textures::ID::Eagle;

        case Aircraft::Type::Raptor:
            return Textures::ID::Raptor;
        }

        return Textures::ID::Eagle;
    }



     void Aircraft::drawCurrent(sf::RenderTarget &target, sf::RenderStates states) const{
         target.draw(mSprite, states);

     }

        Aircraft::Aircraft(Type type, const TextureHolder &textures) : mType(type), mSprite(textures.get(toTextureID(type))) //---------->  this is where i get an error if ResourceHolder.h is not included. Error: Incompatible type
        {
        }

错误:

Incompatible type. 

但这令人困惑。我包括了 ResourceIdentifier.h 有一个类前向声明 ResourceHolder.h , 在我的 Aircraft.h

为什么我会收到错误?一切都联系在一起。 ResourceHolder在不同的文件中也有自己的类声明,我没有在这里包含。但是每个班级都有一个宣言。

另外,texture是对ResourceIdentifier.h上的模板类的引用。为什么我必须再次在Aircraft.cpp上声明ResourceHolder.h?它已经在ResourceIdentifier.h上课了。我没有使用任何模板类对象。这是一个参考。

0 个答案:

没有答案
相关问题