MST

星途 面试题库

面试题:C++中this指针在复杂类结构下成员函数区分对象数据

有一个继承体系,基类 `Base` 有成员变量 `int baseData;` 和成员函数 `void setBaseData(int value)`。派生类 `Derived` 继承自 `Base`,新增成员变量 `int derivedData;` 和成员函数 `void setDerivedData(int value)`。在 `Derived` 类的 `setDerivedData` 函数中,既要通过 `this` 指针设置 `derivedData`,又要调用基类的 `setBaseData` 函数设置 `baseData`,请实现这些函数,并解释 `this` 指针在整个过程中如何确保数据正确地对应到不同对象。
41.3万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#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 指针在整个过程中起到了准确标识和访问对象成员的作用,确保数据正确地对应到不同对象。