下面这段程序中,D类是从B类和C类派生来的,而B类和C类又都是从A类派生的,那么构造函数和析构函数的调用顺序的调用顺序如何?
#include
class A
{
public:
A()
{
cout<<"a\n";
}
int n;
};
class B:public A
{
public:
B()
{
cout<<"b\n";
}
} ;
class C:public A
{
public:
C()
{
cout<<"c\n";
}
};
class D:public B,public C
{
public:
D()
{
cout<<"d\n";
}
};
void main()
{
D d;
d.B::n=100;
d.C::n=200;
cout< cin.get();
}
显示结果:
a
b
a
c
d
100,200
如果是虚基类继承呢?看下面的程序:
#include
class A
{
public:
A()
{
cout<<"a\n";
}
int n;
};
class C:virtual public A
{
public:
C()
{
cout<<"c\n";
}
};
class B:virtual public A
{
public:
B()
{
cout<<"B\n";
}
} ;
class D:virtual public B,virtual public C
{
public:
D()
{
cout<<"d\n";
}
};
void main()
{
D d;
d.B::n=10;
d.C::n=20;
cout< cin.get();
}
运行结果:
a
b
c
d
20,20
通过这两个例子应该对构造函数和析构函数的调用顺序的调用顺序有所了解了吧
阅读(1149) | 评论(2) | 转发(0) |