[英]Having two structs refer to each other's variables in C++
我有兩個不同的結構,我想像這樣相互轉換:
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
,然后使用指針。 盡管似乎我無法從該指針訪問變量x
和y
,因為尚未定義它們。
有沒有一種方法可以在定義它們之前將這些變量添加到struct聲明中? 還是有解決此問題的更好方法?
首先,向前聲明一個結構,並完全聲明另一個。 您需要對前向聲明的類型使用引用或指針,因為編譯器尚無其定義:
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=
函數以返回引用而不是副本,但這不在此問題/答案的范圍之內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.