C++ 运算符 -> 在复数情况下
C++ operator -> in complex numbers case
问题是用两个双精度值 x
和 y
来实现 class Cplx
表示复数的实部和虚部。
子任务之一是实现 operator ->
,描述如下:
(z->re
and z->im
): 获取z
的实部和虚部(必须像z->re = 5
一样实现改变).
我在使用 operator ->
时遇到了麻烦,我从来没有真正理解它是如何工作的,所以我的问题是:->
是如何工作的,何时使用它,以及如何在这个问题中应用这个想法。
以下是您所要求的...但不确定它是否是您想要的:
template <typename T>
struct ReIm
{
const ReIm* operator ->() const { return this; }
ReIm* operator ->() { return this; }
T re;
T im;
};
struct Cplx
{
double x;
double y;
ReIm<double> operator ->() const { return {x, y}; }
ReIm<double&> operator ->() { return {x, y}; }
};
-> 运算符用于取消引用指向对象的指针并在一个运算符中获取成员 variable/function。例如,
Cplx* cplxPointer = new Cplx();
cplxPointer->x = 5;
与
相同
Cplx* cplxPointer = new Cplx();
(*cplxPointer).x = 5;
它只是取消对指针的引用,然后获取成员变量(如果需要,也可以是函数)。除非我误解了你的问题,否则以上内容应该可以帮助你完成作业。
问题是用两个双精度值 x
和 y
来实现 class Cplx
表示复数的实部和虚部。
子任务之一是实现 operator ->
,描述如下:
(z->re
and z->im
): 获取z
的实部和虚部(必须像z->re = 5
一样实现改变).
我在使用 operator ->
时遇到了麻烦,我从来没有真正理解它是如何工作的,所以我的问题是:->
是如何工作的,何时使用它,以及如何在这个问题中应用这个想法。
以下是您所要求的...但不确定它是否是您想要的:
template <typename T>
struct ReIm
{
const ReIm* operator ->() const { return this; }
ReIm* operator ->() { return this; }
T re;
T im;
};
struct Cplx
{
double x;
double y;
ReIm<double> operator ->() const { return {x, y}; }
ReIm<double&> operator ->() { return {x, y}; }
};
-> 运算符用于取消引用指向对象的指针并在一个运算符中获取成员 variable/function。例如,
Cplx* cplxPointer = new Cplx();
cplxPointer->x = 5;
与
相同Cplx* cplxPointer = new Cplx();
(*cplxPointer).x = 5;
它只是取消对指针的引用,然后获取成员变量(如果需要,也可以是函数)。除非我误解了你的问题,否则以上内容应该可以帮助你完成作业。