开发者

cyclic includes, how can I resolve this without changing class hierarchy

            Animal
               |
           Mammal
               / \
      TwoLegged - FourLegged
         /           \
        Human      Lion

I have this class hierarchy, each class defined in it's own header. Now when I include both Human.h and Lion.h in the same place, I get a Mammal redefinition error.

 error C2011: 'Mammal' : 'class' type redefinition

This because Mammal.h is included in both TwoLegged and OneLegged classes.

I'm not sure however, how I could resolve this cyclic dependency in headers, as I cannot change the class hierarchy.

Anybody care to assist?

EDIT:

Mammal header

#ifndef MAMMAL_H
#define MAMNAL_H

#include "stdafx.h"
#include "Animal.h"

class Mammal : public Animal
{
public:
    Mammal::Mammal();
    virtual Mammal::~Mammal();

    std::string mammal_name();
    int mammal_age();
    int mammal_expectedlifedays();
    bool mammal_hunter();
    int mammal_power();
    int mammal_birthrate();
    bool mammal_alive();

protected:
    Mammal::Mammal(const std::string& mname, int mexpectedlifedays, int mage, bool mhunter, int mpower, int mbirthrate, bool malive) : Animal(mname, mexpectedlifedays, mage,mhunter,  mpower, mbirthrate开发者_如何学编程, malive)
    {}
private:
};

#endif

The errors given by the compiler:

error C2011: 'Mammal' : 'class' type redefinition
see declaration of 'Mammal'

error C2504: 'Mammal' : base class undefined
error C2614: 'TwoLegged' : illegal member initialization: 'Mammal' is not a base or member

Note: It's not homework, else I would have tagged it as such.


#pragma once

Add that at the very top of all your header files.

However, keep in mind that even though it is very well supported by compilers, it's not a standard.


You need to use include guards. The typical form is:

#ifndef NAME_OF_HEADER_H
#define NAME_OF_HEADER_H

// Rest of header code here.

#endif

Since #include in C++ just does a copy-paste of the text in the current file if the same header gets included twice that text will result in duplicate class definitions. What the include guard does is prevent the multiple inclusion of the same header.

EDIT: The problem is that you check for definition of MAMMAL_H and then define MAMNAL_H (note the N in the defined version). I always copy-paste to generate my include guards for precisely this reason.


I guess you forgot include guards. Use #ifndef /#ifdef/ #endif as John suggested.


#ifndef MAMMAL_H
#define MAMMAL_H



... definition of mammal


#endif
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜