65,206
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
using namespace std;
class A
{
public:
A() { cout << "A: " << this << endl; }
virtual ~A() {}
virtual void say() { cout << "A!" << endl; }
protected:
int i;
};
A* g_p = 0;
class D
{
public:
D() { cout << "D: " << this << endl; }
virtual ~D() {}
virtual void say() { cout << "D!" << endl; }
protected:
char c;
};
class B : public D
{
public:
B() { g_p = reinterpret_cast<A*>(this); cout << "B: " << this << endl; }
virtual ~B() {}
virtual void say() { cout << "B!" << endl; }
protected:
int i;
char c[100];
};
class C : public A, public B
{
public:
C() { cout << "C: " << this << endl; }
virtual ~C() {}
virtual void say() { cout << "C!" << endl; }
protected:
float f;
int i;
char c[256];
};
int main()
{
C c;
cout << "问题是:g_p != &c : " << g_p << " != " << &c << endl;
if (g_p != NULL) g_p->say();
return 0;
}
#include <iostream>
using namespace std;
class A
{
public:
A() {
cout << "A: " << this << endl;
}
virtual ~A() {}
virtual void say() { cout << "A!" << endl; }
protected:
int i;
};
A* g_p = 0;
class D
{
public:
D() { cout << "D: " << this << endl; }
virtual ~D() {}
virtual void say() { cout << "D!" << endl; }
protected:
char c;
};
class C;
class B : public D
{
public:
B() {
static int nOffset = 0;
if (nOffset == 0) {
class DerivedA : public A {
// helper class to find the position of vptr in A
public:
virtual ~DerivedA() {};
};
A a;
DerivedA da;
a = da;
// now, between the layout of da and a, only vptr is different
int nSizeA = sizeof(A);
// Calculate the position of vptr in A
int nVptrOffset;
int nVptrValue;
for (int i=0; i<nSizeA/4; i++) {
int *pr1 = (int *)&a + i;
int *pr2 = (int *)&da + i;
if (*pr1 != *pr2) {
nVptrOffset = i*4;
nVptrValue = *pr1;
break;
}
}
// scan in the neighbour for the vptr of A
int *pFirst = (int *)this;
int *pSecond = (int *)((char *)this + sizeof(B));
for (int i=0; i<100; i++) {
if (*pFirst == nVptrValue) {
nOffset = ((char *)pFirst - (char *)this);
break;
}
else if (*pSecond == nVptrValue) {
nOffset = ((char *)pSecond - (char *)this);
break;
}
pFirst --;
pSecond ++;
}
if (nOffset != 0)
nOffset -= nVptrOffset;
}
if (nOffset != 0) {
g_p = (A*)((char *)this + nOffset);
}
else {
g_p = NULL;
}
};
virtual ~B() {}
virtual void say() { cout << "B!" << endl; }
protected:
int i;
char c[100];
};
class Tmp
{
int m[5];
};
class C : public A,public Tmp, public B
{
public:
C() { cout << "C: " << this << endl; }
virtual ~C() {}
virtual void say() { cout << "C!" << endl; }
protected:
float f;
int i;
char c[256];
};
int main()
{
C c;
cout << "Problem: g_p != &c : " << g_p << " != " << &c << endl;
if (g_p != NULL) g_p->say();
return 0;
}
B() {
class Proxy:public A,public B
{
};
Proxy * p =(Proxy*)this;
g_p = (A*)p;
cout << "B: " << this << endl;
}