我正在阅读老师给我的一些代码,但我不太理解特定的一行代码。该函数返回一个 int&。
return (*(Vector *)this)[i];
此返回语句位于“[]”的运算符重载中。还有另一个运算符重载 [] 是在“this”的基类中定义的。基类是定义的类“Vector”。我不明白这行代码。
最佳答案
如有疑问,请简化。
第一步:
return (*(Vector *)this)[i];
可以
Vector* ptr = (Vector*)this;
return (*ptr)[i];
第二步:
return (*ptr)[i];
可以
Vector& ref = *ptr;
return ref[i];
两种简化放在一起,这条线
return (*(Vector *)this)[i];
相当于
Vector* ptr = (Vector*)this;
Vector& ref = *ptr;
return ref[i];
当成员函数是const
成员函数时,this
的类型是Vector const* const
。
第一行删除了对象指针的const
-ness。
第二行取消引用指针。
最后一行返回对象的第 i
个元素。
关于c++ - 不明白这个返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58141053/