class NoVirtualClass
{
public:
NoVirtualClass()
{
std::cout << " NoVirtualClass " << endl;
}
~NoVirtualClass()
{
std::cout << " ~NoVirtualClass " << endl;
}
};
class VirtualClass
{
public:
VirtualClass()
{
std::cout << " VirtualClass " << endl;
}
~VirtualClass()
{
std::cout << " ~VirtualClass " << endl;
}
};
class subClass: public NoVirtualClass, virtual public VirtualClass
{
public:
subClass()
{
std::cout << " subClass" << endl;
}
~subClass()
{
std::cout << " ~subClass" << endl;
}
};
class A
{
public:
A()
{
std::cout << "A" << endl;
}
~A()
{
std::cout << "~A" << endl;
}
};
class C
{
public:
C()
{
std::cout << "C" << endl;
}
~C()
{
std::cout << "~C" << endl;
}
};
class B: public A
{
public:
B()
{
std::cout << "B" << endl;
}
~B()
{
std::cout << "~B" << endl;
}
private:
C c;
};
struct stA
{
stA()
{
cout << "stA" << endl;
}
};
struct stB : stA
{
stB()
{
cout << "stB" << endl;
}
};
struct stC
{
stC()
{
cout << "stC" << endl;
}
};
struct stD: stB
{
stD()
{
cout << "stD" << endl;
}
};
struct stE
{
struct stA a;
struct stC c;
struct stD d;
stE()
{
cout << "stE" << endl;
}
};
void funRec(int i)
{
if(i < 5)
{
funRec(++i);
}
cout << " " << i ;
return;
}
int main(void)
{
subClass sub;
volatile char *pvch = new volatile char[10];
delete pvch;
cout << endl;
B b;
cout << endl;
struct stE e;
cout << endl;
funRec(1);
cout << endl;
cout << endl;
return 0;
}
Output:
VirtualClass
NoVirtualClass
subClass
A
C
B
stA
stC
stA
stB
stD
stE
5 5 4 3 2
~B
~C
~A
~subClass
~NoVirtualClass
~VirtualClass
刘峰六点评:
(1) 如果有多个父类,其中有虚继承的情况下,不管初始化列表的顺序如何,都会先初始化虚继承的基类,在初始化非虚继承的基类
(2) 如果有类中含有类成员,那么顺序是(1) 基类 (2) 子类类成员 (3)子类
(3) 如果有递归调用,函数的局部变量不会随递归调用的对局部变量的改变而改变,当时是几就是几
阅读(2206) | 评论(1) | 转发(0) |