我对理解基于虚空/多态的程序的执行顺序有疑问。
据我了解其他输出会发生什么,我不知道为什么使用这些命令:
a->b();
d->b();
d->a();
((G*)d) -> a();
提供以下输出:
Nieznany
Nieznany
Gniewosz
任何人都可以解释一下为什么这三种方法打印出上面的结果吗?
#include <iostream>
using namespace std;
class C { public:
C() {cout << "Buduje A";}
void a() {cout << "Nauczyciel" << endl;}
virtual ~C() {cout << "~D" << endl;}
virtual void b() {cout << "Nieznany" << endl; }; };
class G {
int e; public:
G() {cout << "Buduje G ";}
void a() {cout << "Gniewosz " << endl;}
~G() {cout << "~C " << endl; }
void b() {cout << "Draka" << endl;}; };
class A :public C {
int o;
int a;
public:
A() {cout << "Buduje C ";}
~A() {cout << "~F " << endl;} };
class D :public A {
float f; public:
D() {cout << "Buduje D";}
virtual void a() {cout << "Pośrednik" << endl;}
~D() {cout << "~E" << endl;} };
class B :public D {
short s;
int b; public:
B() {cout << "Buduje E ";}
~B() {cout << "~G" << endl;} };
class E :public B {
E() {cout << "Buduje B";}
~E() {cout << "~I" << endl;} };
class F :public G, public D { public:
F() {cout << "Buduje F ";}
void a() {cout << "Nieznany " << endl;}
void b() {}
~F() {cout << "~H" << endl;} };
void nic() {cout << endl;}
int main() {
C*a = new B();
nic();
a->b();
D*d = new F;
nic();
d->b();
d->a();
((G*)d) -> a();
delete d;
delete a;
return 0; }