品牌网站建设新闻,wordpress 显示指定文章,wordpress载入动画,四川公司网站建设招标虚表生成在父类构造完之后#xff0c;子类构造之前
#xff0c;生成父类虚表#xff0c;再执行子类的构造#xff0c;这时虚表已经重写#xff0c;可以多态#xff08;即开始派生类构造初始化列表代码#xff09;。
验证#xff1a;输出This is animal miao miao mia…虚表生成在父类构造完之后子类构造之前
生成父类虚表再执行子类的构造这时虚表已经重写可以多态即开始派生类构造初始化列表代码。
验证输出This is animal miao miao miao
1 #includeiostream
using std::cout;
using std::cin;
using std::endl;
struct Animal
{virtual int callOut()const{cout This is animal ;return 0;}Animal(){callOut();}
};
class Cat:public Animal
{virtual int callOut()const{cout miao miao miao endl;return 1;}int a;
public:Cat():a(callOut()){cout a endl;}};
int main()
{const Animal cat Cat();return 0;
}
//错题
class A{public:A ():m_iVal(0){test();}virtual void func() { std::coutm_iVal‘ ’;}void test(){func();}public:int m_iVal;};class B : public A{public:B(){test();}virtual void func(){m_iVal;std::coutm_iVal‘ ’;}};int main(int argc ,char* argv[]){A*p new B;p-test();return 0;} 运行结果012
分析:new B时先调用父类A的构造函数执行test()函数在调用func()函数由于此时还处于对象构造阶段多态机制还没有生效所以此时执行的func函数为父类的func函数打印0构造完父类后执行子类构造函数又调用test函数然后又执行func(),由于父类已经构造完毕虚表已经生成func满足多态的条件所以调用子类的func函数对成员m_iVal加1进行打印所以打印1 最终通过父类指针p-test(),也是执行子类的func,所以会增加m_iVal的值最终打印2 所以答案为C 0 1 2