有两个结构在C++中相互引用彼此的变量

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

本文关键字:引用 变量 C++ 两个 结构      更新时间:2023-10-16

我有两个不同的结构,我想像这样相互转换:

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

我想我需要做一些类似下面代码的事情:

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;
};

但问题是PointF在声明之前使用了PointI。根据我在其他问题中所读到的内容,我了解到我可以在定义两个结构之前声明PointI,然后使用指针。尽管我似乎无法从该指针访问变量xy,因为它们还没有定义。

有没有一种方法可以在定义这些变量之前将它们添加到结构声明中?或者有更好的方法来解决这个问题吗?

首先,正向声明其中一个结构,并完全声明另一个结构。您需要对正向声明的类型使用引用或指针,因为编译器还没有定义:

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

接下来,您需要完全声明转发声明的结构:

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

现在,您可以继续定义每个的operator=函数:

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;
}

请注意,您应该更改operator=函数以返回引用而不是副本,但这超出了本问答的范围。