Skip to main content
 首页 » 编程设计

c++之在 C++ 中,有两个结构引用彼此的变量

2024年12月31日17kevingrace

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

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= 函数以返回引用而不是拷贝,但这超出了本问题/答案的范围。