#include "stdafx.h"
#include <iostream>
using namespace std;
class Parent
{
public:
Parent()
{
this->printfn();
}
virtual ~Parent(){}
virtual void printfn()
{
cout <<"1 ";
}
void test_again(){printfn();}
};
class Son : public Parent
{
public:
void printfn()
{
cout <<"2 ";
}
Son()
{
printfn();
}
~Son(){}
};
int main(int argc, char* argv[])
{
Parent* p = new Son();//构造函数中无法实现多态,因为子类对象都没有完全创建成功
p->test_again();//子类已经构造完成
int sign = 1;
//switch中default不是必须的
switch(sign)
{
case 1:cout<<"123"<<endl;break;
case 2:break;
}
return 0;
}
子类构造时,先会调用父类构造函数,父类构造函数中调用printfn,它是一个虚函数,但是此时子类还处于构造过程中并没有构建完成,因此无法调用派生类的实现,只能调用父类本身的实现,我们看到的就是无法呈现多态了。这里将会输出1 2.
另外,通常在写switch时,自己都会写上default语句,防止传入异常数据,一直都这么用了。结果笔试有这么个题,说default语句不是必须的,我却认为是错的。结果写了点代码一测,发现是对的。这个人人觉得知道就好了,写的时候还是写上default.