C ++ compilation error enum "does not name type"

The following code:

foo.h

#include "bar.h"
class foo{ 
public:
   enum my_enum_type { ONE, TWO, THREE }; 
   foo(); 
   ~foo() {} 
};

foo.cpp

foo::foo()
{
   int i = bar::MY_DEFINE;
}

bar.h

#include "foo.h"
class bar{
public:
   static const int MY_DEFINE = 10;
   foo::my_enum_type var;
   bar() {};
   ~bar() {};
};

Causes the g ++ compiler to complain about my_enum_type "not calling type". What for? All headers have multiple inclusion (not shown here for clarity).

thank

+3
source share
3 answers

You must remove the circular dependency, so you need to consider foo.cpp and foo.h as different units for this purpose.

  • The class definition bar should see foo :: my_enum_type, so probably bar.h, including foo.h, is a must.

  • The class definition foo does not use any of the bars, so foo.h does not need to include bar.h

  • foo.cpp MY_DEFINE, foo.cpp bar.h. foo.h , foo.cpp, , .

, .

+2

:

  • ,

foo.h C, .

foo.h :

> cpp foo.h
class bar{ // preprocessed from #include "bar.h"
public:
   static const int MY_DEFINE = 10;
   foo::my_enum_type var;
   bar() {};
   ~bar() {};
};
// end of #include "bar.h"
class foo{ 
public:
   enum my_enum_type { ONE, TWO, THREE }; 
   foo(); 
   ~foo() {} 
};

, , ++. foo . ++, Java, , .

  • . #ifndef #pragma once
  • bar.h foo.h.
  • ( bar foo.h, ).
  • *.cpp.

, PIMPL.

- #include "bar.h" foo.h

+4
foo()
{
   int i = bar::MY_DEFINE;
}

foo::foo()
{
   //...
}

,

static const int MY_DEFINE = 10;

, . bar.cpp

const int bar::MY_DEFINE;

bar.h foo.h foo.h bar.h... :)

+2
source

Source: https://habr.com/ru/post/1771678/


All Articles