有两个结构在C++中相互引用彼此的变量
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 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=
函数以返回引用而不是副本,但这超出了本问答的范围。
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 多个"常量引用"变量可以共享同一个内存吗?
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- C++方法中的引用变量
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 使用更改此变量的函数在同一行中打印引用变量
- 将延迟变量分配给引用变量
- 如何通过引用获取引用变量的地址?
- 将引用变量传递给函数
- C++中引用变量的内存?
- 按名称存储和引用变量列表
- 返回一个C++引用变量 VS 返回一个变量
- c++ 在 if 语句中分配引用变量
- 引用变量何时合适,为什么?你能解释一下实际的语法和位置吗?
- C++ - 将一个变量分配给另一个变量和将变量分配给引用变量有什么区别?
- 在类范围内声明时,应在 C++14 中引用变量模板
- 当引用变量的引用"死亡"时,它会发生什么?
- 将非按引用变量分配给返回按引用的函数,反之亦然
- 引用变量如何存储在mem中
- 引用变量存储在哪里