面试题答案
一键面试#include <iostream>
class Base {
private:
int baseData;
public:
void setBaseData(int value) {
baseData = value;
}
};
class Derived : public Base {
private:
int derivedData;
public:
void setDerivedData(int value) {
this->derivedData = value;
this->setBaseData(value);
}
};
this
指针是一个隐含指针,它指向调用成员函数的对象。在 Derived
类的 setDerivedData
函数中,this->derivedData = value;
通过 this
指针明确地将 value
赋值给当前对象的 derivedData
成员变量。而 this->setBaseData(value);
则通过 this
指针调用基类的 setBaseData
函数,这样可以确保 setBaseData
函数操作的是当前 Derived
对象从 Base
类继承而来的 baseData
成员变量。因此,this
指针在整个过程中起到了准确标识和访问对象成员的作用,确保数据正确地对应到不同对象。