C++之继承类中的this指针

本文通过具体的C++代码示例,探讨了类继承中this指针的行为特性及其在抽象类与虚函数环境下的表现差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<typeinfo>
using namespace std;

class A {
public:
    A() {
        cout << this << endl;
        cout << typeid(this).name() << endl;
        cout << "&a = " << &a << endl;
        cout << "----------------------" << endl;
    }
    int a;
};
class B:public A {
public:
    B() {
        cout << this << endl;
        cout << typeid(this).name() << endl;
        cout << "&a = " << &a << endl;
        cout << "&b = " << &b << endl;
        cout << "----------------------" << endl;
    }
    int b;
};
class C :public B {
public:
    C() {
        cout << this << endl;
        cout << typeid(this).name() << endl;
        cout << "&a = " << &a << endl;
        cout << "&b = " << &b << endl;
        cout << "&c = " << &c << endl;
        cout << "----------------------" << endl;
    }
    int c;
};

int main() {
    A *pa = new C;
    delete pa;

    system("pause");
    return 0;
}

输出结果:

这里写图片描述

可以看到A B C 的this指针的地址都是相同的(与成员变量a的地址相同),但类型是不同的。

如果A是抽象类呢:

#include<iostream>
#include<typeinfo>
using namespace std;

class A {
public:
    A() {
        cout << this << endl;
        cout << typeid(this).name() << endl;
        cout << "&a = " << &a << endl;
        cout << "----------------------" << endl;
    }
    virtual void fun() = 0;
    int a;
};
class B:public A {
public:
    B() {
        cout << this << endl;
        cout << typeid(this).name() << endl;
        cout << "&a = " << &a << endl;
        cout << "&b = " << &b << endl;
        cout << "----------------------" << endl;
    }
    void fun() {}
    int b;
};
class C :public B {
public:
    C() {
        cout << this << endl;
        cout << typeid(this).name() << endl;
        cout << "&a = " << &a << endl;
        cout << "&b = " << &b << endl;
        cout << "&c = " << &c << endl;
        cout << "----------------------" << endl;
    }
    int c;
};

int main() {
    A *pa = new C;
    delete pa;

    system("pause");
    return 0;
}

输出结果:

这里写图片描述

可以看到A B C 的this指针的地址都是相同的,但这里不再等于成员变量a的地址,应该是多了一个虚函数指针,偏移了4个字节,所以成员变量a的地址在this指针的基础上又加了4个字节,同样类型不相同。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值