开发者

C++: structs across classes

I have two classes: MazeClass and CreatureClass, that use a struct called "coordinates," how am I able to use the struct across both classes? I've tried to put the struct in twice and I get:

MazeClass.h:16:8: error: redefinition of ‘struct coordinate’

CreatureClass.h:11:18: error: previous 开发者_如何学Godefinition of ‘struct coordinate’


You should only define the struct once across your header files. Move coordinates into its own header file (with an include guard), then include that header in both of your other headers.

Example coordinates.h:

#ifndef COORDINATES_H
#define COORDINATES_H

struct coordinates {
    // ...
};

#endif

Technically, it's OK to define coordinates in two headers (though horrible from a maintainability perspective -- stay DRY!). The problems arise when another header or implementation file includes both of those headers (either directly or indirectly) -- then the compiler sees two different coordinates struct definitions (it doesn't know they're the same), and complains with the errors you've posted.


You can declare the struct in one of the classes in public. Choose the class that is more relevant:

class MazeClass
{
public:
    struct coordinate {} ;
} ;

Other classes can access this type as MazeClass::coordinate. Alternatively you can bring it with a typedef.

class CreatureClass
{
public:
    typedef MazeClass::coordinate coordinate ;
} ;


You need to put the definition of struct coordinate in a single common location instead of duplicating it. Maybe create a new coordinate.h file? Don't forget to use include guards.


In algebra this is called "factoring out" the common factors.

Create a "coordinate.h" file. in it, using include guards, place the definition of your coordinate struct.

Then use #include "coordinate.h" in both MazeClass.h and CreatureClass.h.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜