0

Let's say, I have two simple classes: integer with just one int variable in it, and real with double. I'm already done so that

integer a=2016; int b=a;

real a=20.16; double b=a;

working perfectly. Now I have to do the conversion between them, like so:

integer foo; real bar; foo=bar; bar=foo;

Or at least with similar syntax. I know that there will be loss of some data when converting double to int, I'll deal with it. So how can I do that? What and where should I #include and what the methods/operator overloads to write? My project is divided into files main.cpp, integer.h, integer.cpp, real.h, real.cpp. Thanks.

EDIT: The classes looks like:

//integer.h
class integer
{
    private:
        int a;
    public:
        integer();
        integer(int number);
        operator int() const;
};
//integer.cpp
#include "integer.h"

integer::integer(){
    a=0;
}
integer::integer(int number){
    a=number;
}
integer::operator int() const{
    return a;
}
//real.h
class real {
    private:
        double a;
    public:
        real();
        real(double number);
        operator double() const;
};
//real.cpp
#include "real.h"

real::real(){
    a=0;
}
real::real(double number){
    a=number;
}
real::operator double() const{
    return a;
}
1valdis
  • 1,009
  • 1
  • 15
  • 27

1 Answers1

2

You basically have two solutions to your problem:

The first is to write conversion operators that can convert a real object to an integer object, and vice versa.

The other solution is to implement custom constructors and assignment operators to take the other class.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I've tried to do like in first example of "Explanation", got "Incomplete type used in nested name specifier". How to do the second variant? – 1valdis Sep 14 '16 at 13:57
  • @1valdis Only put the conversion operator function ***declarations*** in the class. Then ***define*** (i.e. implement) the function after both classes are fully defined. – Some programmer dude Sep 14 '16 at 14:43
  • I did declare functions in headers, defined in their .cpp's. Where else should I do that? – 1valdis Sep 14 '16 at 14:50
  • @1valdis You do remember to add forward declarations of the classes, not including the header files into each other and thereby creating a circular dependency? See e.g. [this simple example on how it could be done](http://ideone.com/JnL92S). – Some programmer dude Sep 14 '16 at 15:13
  • Yes, I write class real; before class integer{...} and so on. – 1valdis Sep 14 '16 at 15:15