0

I have two header files. decimal.h and integer.h each containing their respective classes. I want to write something like this.

//integer.h
#ifndef INTEGER_H
#define INTEGER_H
#include "decimal.h"
class Integer
{
     ...
     operator Decimal();
}
#endif

//decimal.h
#ifndef DECIMAL_H
#define DECIMAL_H
#include "integer.h"
class Decimal
{
     ...
     operator Integer();
}
#endif

What is giving me the trouble is that since they are including each over it behaves strangely in Visual Studio and an generate strange compiler errors. Is there any way around this?

stefan
  • 10,215
  • 4
  • 49
  • 90
chasep255
  • 11,745
  • 8
  • 58
  • 115
  • Never a good design to do this. Try to isolate them. – Abhineet Dec 06 '13 at 13:38
  • You should add the exact error messages as part of your question, as many things in Visual Studio could be considered "strange"... – badgerr Dec 06 '13 at 13:55
  • @badgerr - regardless of your subjective judgments, the problem here is clear, and the error messages that this kind of mistake produces are often "strange", even with your favorite compiler. – Pete Becker Dec 06 '13 at 14:45

1 Answers1

6

Maybe you want just a forward declaration?

// In Integer.h
class Decimal;
class Integer
{
     ...
     operator Decimal();
};

(You missed the last semicolon in your code, by the way.)

Yongwei Wu
  • 5,292
  • 37
  • 49
  • Oops. I'm used to java and I didn't copy and paste from an editor. Also for that to work the need to both be in the same header right? – chasep255 Dec 06 '13 at 14:02
  • Yes. The shown code is supposed to be in Integer.h. Do the same in Decimal.h. – Yongwei Wu Dec 06 '13 at 14:15
  • Re: "Do the same in Decimal.h" - good advice, but note that that's not technically necessary to get rid of the problem; the original version of `Decimal.h` will work fine, so long as `Integer` doesn't try to `#include` it. – Pete Becker Dec 06 '13 at 14:48
  • @PeteBecker: You are absolutely correct. I just like to reduce dependencies as far as possible (maybe a weakness in C/C++). Nice to see you around here :-). – Yongwei Wu Dec 07 '13 at 03:24