Having two structs refer to each other's variables in C++

3.4k Views Asked by At

I have two different structs which I want to convert to each other like this:

PointI a = PointI(3,5);
PointF b = a;

I assume that I will need to do something like the code below:

struct PointF
{
    PointF operator=(PointI point){
        x = point.x;
        y = point.y;
        return *this;
    }
    float x, y;
};

struct PointI
{
    PointI operator=(PointF point)
    {
        x = point.x;
        y = point.y;
        return *this;
    }
    int x, y;
};

But the problem is that PointF uses PointI before it is declared. From what I've read in other questions, I understand that I can declare PointI before defining both structs, and then use a pointer. Though it seems that I won't be able to access the variables x and y from that pointer, as these are not defined yet.

Is there a way I can add these variables to the struct declaration before defining them? Or is there a better way to solve this problem?

1

There are 1 best solutions below

8
On BEST ANSWER

First, forward declare one of the structs and fully declare the other. You'll need to use either a reference or pointer for the forward declared type, since the compiler doesn't have its definition yet:

struct PointI;
struct PointF
{
    PointF operator=(const PointI& point);
    float x, y;
};

Next, you need to fully declare the struct you forward declared:

struct PointI
{
    PointI operator=(const PointF& point);
    int x, y;
};

Now you can go ahead and define the operator= functions for each:

PointF PointF::operator=(const PointI& point)
{
    x = point.x;
    y = point.y;
    return *this;
}

PointI PointI::operator=(const PointF& point)
{
    x = point.x;
    y = point.y;
    return *this;
}

Note that you should change your operator= functions to return references rather than copies, but that's outside the scope of this question/answer.