您的位置:首页 > 编程语言 > C语言/C++

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

2016-06-14 19:49 375 查看
#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个字节,同样类型不相同。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: