#include <iostream>
using namespace std;
class a
{
public:
a();
void display();
};
a::a()
{
cout<<"a.............."<<endl;
}
void a::display()
{
cout<<"a::display"<<endl;
}
class b : public a
{
public:
b();
void display();
};
b::b()
{
cout<<"b.............."<<endl;
}
void b::display()
{
cout<<"b::display"<<endl;
}
class c : public a
{
public:
c();
void display();
};
c::c()
{
cout<<"c.............."<<endl;
}
void c::display()
{
cout<<"c::display"<<endl;
}
int main(void)
{
b* objb = new b;
c* objc = (c*)objb;
objc->display();
return 0;
}
执行结果:
a..............
b..............
c::display
我想知道在转换的时候它是如何转换的,原理是什么,在内存中是如何来分配的?
如果将程序改成这样,将a中的display改在虚函数,则这样:
#include <iostream>
using namespace std;
class a
{
public:
a();
virtual void display();
};
a::a()
{
cout<<"a.............."<<endl;
}
void a::display()
{
cout<<"a::display"<<endl;
}
class b : public a
{
public:
b();
void display();
};
b::b()
{
cout<<"b.............."<<endl;
}
void b::display()
{
cout<<"b::display"<<endl;
}
class c : public a
{
public:
c();
void display();
};
c::c()
{
cout<<"c.............."<<endl;
}
void c::display()
{
cout<<"c::display"<<endl;
}
int main(void)
{
b* objb = new b;
c* objc = (c*)objb;
objc->display();
return 0;
}
执行结果:
a..............
b..............
b::display
我也这个时候肯定与晚绑定,多态有关,但还是不太明白,请哪位高手指点一下.谢谢!