64,642
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class A
{
public:
virtual void f()
{
cout<<"A"<<endl;
}
};
class B: public A
{
public:
virtual void f()
{
cout<<"B"<<endl;
}
};
A a_g; //全局对象
int main()
{
static A a_s; //静态对象
A a_l; //局部对象
B b;
*(void **)(&a_g) = *(void**)(&b); //改变虚函数表指针
*(void **)(&a_s) = *(void**)(&b);
*(void **)(&a_l) = *(void**)(&b);
a_g.f(); //输出A
a_s.f(); //输出A
a_l.f(); //输出A
A &a_h = *(new A); //堆对象
*(void **)(&a_h) = *(void**)(&b);
a_h.f(); //输出B
(static_cast<B&>(a_l)).f(); //输出B
A a_r; //不改变虚函数表指针.
(static_cast<B&>(a_r)).f(); //输出A
}
*(void **)(&a_g) = *(void**)(&b); //改变虚函数表指针
*(void **)(&a_s) = *(void**)(&b);
*(void **)(&a_l) = *(void**)(&b);
#include <iostream>
using namespace std;
class A
{
public:
virtual void fun()
{
cout << "A's fun()" << endl;
}
};
class B : public A
{
public:
void fun()
{
cout << "B's fun()" << endl;
}
};
int main(void)
{
A a;
B b;
a.fun();
b.fun();
((A)b).fun();
((A*)&b)->fun();
return 0;
}
class A
{
public:
virtual void v_f(){ cout<<"this is A"<<endl; }
};
class B:public A
{
public:
virtual void v_f(){ cout<<"this is B"<<endl; }
void m_f(){ cout<<"this is B's member func"<<endl; }
};
A* pa_g;
B* pb_g;
int main(int argc, char **argv)
{
A* pa_l;
B* pb_l;
pb_l->m_f(); //调用一般成员函数,函数寻址不需要对象,只要类型
pb_g->m_f();
pa_l->v_f(); //调用虚函数必须借助虚表指针间接寻址,因此需要对象,这里因为没对象而崩掉
pa_g->v_f();
return 0;
}