Beispiel #1
0
int main(void)
{
	Animal *animal = NULL;
	animal = new Dog;
	animal->cry();
	animal->doWork();
	cout << " -----" << endl;
	Dog * dog = NULL;
	dog = dynamic_cast<Dog*>(animal); //dynamic_cast是将父类指针转换成子类指针
	if (dog != NULL) {
		cout << "转换成功" << endl;
		dog->cry();
		dog->doWork();
	}
	else {
		cout << "转换失败" << endl;
	}
	Cat *cat = NULL;
	//想通过dynamic_cast 将animal转换成一个cat指针
	cat = dynamic_cast<Cat*>(animal); //通过将animal指针转换成Cat指针
	//尝试将一只狗转换成一只猫
	if (cat != NULL) {
		cout << "转换成功" << endl;
		cat->cry();
		cat->doWork();
	}
	else {
		cout << "转换失败" << endl;
	}
	delete animal;
	return 0;
}
// http://d.pr/n/16sMV
int main()
{
	Animal a; Dog d;
	cout << sizeof(a) << endl;
	cout << sizeof(d) << endl;


	Animal* p = &d;
	p->cry();       // 이 순간의 정확한 원리를 생각해 봅시다.
	// (*p)[0](p);
}
int main( )
{
    string nam;
    char s;
    cin>>nam>>s;
    Animal *p;
    Mouse m1(nam, s);
    p=&m1;
    p->cry();
    cin>>nam>>s;
    Mouse m2(nam, s);
    p=&m2;
    p->cry();
    cin>>nam>>s;
    Cat c1(nam, s);
    p=&c1;
    p->cry();
    cin>>nam>>s;
    Dog d1(nam, s);
    p=&d1;
    p->cry();
    return 0;
}