Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: structs across classes

Tags:

c++

class

struct

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 definition of ‘struct coordinate’

like image 684
Athetius Avatar asked Jan 20 '23 04:01

Athetius


2 Answers

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.

like image 187
Cameron Avatar answered Jan 30 '23 08:01

Cameron


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 ;
} ;
like image 40
Tugrul Ates Avatar answered Jan 30 '23 08:01

Tugrul Ates