dth*_*guy 0 c++ inheritance class
我正在阅读老师给我的一些代码,但我不太了解其中一行特定的代码。该函数返回一个int&。
return (*(Vector *)this)[i];
Run Code Online (Sandbox Code Playgroud)
此return语句的运算符重载为“ []”。[]的另一个操作符重载在“ this”的基类中定义。基类是已定义的类“ Vector”。我不明白这行代码。
如有疑问,请简化。
第一步:
return (*(Vector *)this)[i];
Run Code Online (Sandbox Code Playgroud)
可
Vector* ptr = (Vector*)this;
return (*ptr)[i];
Run Code Online (Sandbox Code Playgroud)
第二步:
return (*ptr)[i];
Run Code Online (Sandbox Code Playgroud)
可
Vector& ref = *ptr;
return ref[i];
Run Code Online (Sandbox Code Playgroud)
两种简化放在一起,线
return (*(Vector *)this)[i];
Run Code Online (Sandbox Code Playgroud)
相当于
Vector* ptr = (Vector*)this;
Vector& ref = *ptr;
return ref[i];
Run Code Online (Sandbox Code Playgroud)
当成员函数是const成员函数时,this类型为Vector const* const。
第一行删除const对象指针的-ness。
第二行取消引用指针。
最后一行返回i对象的-th元素。