我对以下代码段和输出有一些理解问题。任何人都可以提供一个解释,主要是为什么 test() 以输出中看到的方式工作。我正在使用 MSCV 2008 C++ 编译器。
class AS
{
int a;
public:
AS():a(1){show();}
virtual void show() {cout<<a<<endl;}
void test() { cout<<"Calling show()"<<endl; this->show();}
};
class BS: virtual public AS
{
int b;
public:
BS():b(2){show();}
virtual void show() {cout<<b<<endl;}
void test() { cout<<"Calling show()"<<endl; this->show();}
};
class CS:public virtual AS
{
int c;
public:
CS():c(3){show();}
virtual void show() {cout<<c<<endl;}
void test() { cout<<"Calling show()"<<endl; this->show();}
};
class DS:BS, public CS
{
int d;
public:
DS():d(4){show();}
virtual void show() {cout<<d<<endl;}
void test() { cout<<"Calling show()"<<endl; this->show();}
};
int main()
{
cout<<"Class Sizes:"<<endl;
cout<<sizeof(AS)<<endl;
cout<<sizeof(BS)<<endl;
cout<<sizeof(CS)<<endl;
cout<<sizeof(DS)<<endl;
AS* aa = new DS();
aa->test();
aa->show();
delete aa;
return 0;
}
输出是: -
Class Sizes:
8
20
20
32
1
2
3
4
Calling show()
4
4
以及删除aa的断点异常;为什么 ?