继承多态笔试题实战分析

class Animal
{
public:
	Animal(string name) : _name(name) {}
	virtual void bark() {}
protected:
	string _name;
};
//以下是动物实体类
class Cat : public Animal
{
public:
	Cat(string name) :Animal(name) {}
	void bark() { cout << _name << " bark: miao miao!" << endl; }
};

class Dog : public Animal
{
public:
	Dog(string name) :Animal(name) {}
	void bark() { cout << _name << "bark: wang wang" << endl; }
};

class Pig : public Animal
{
public:
	Pig(string name) :Animal(name) {}
	void bark() { cout << _name << "bark: heng heng" << endl; }
};

int main()
{
	Animal *p1 = new Cat("加菲猫");
	Animal *p2 = new Dog("二哈");

	int *p11 = (int*)p1;
	int *p22 = (int*)p2;
	int tmp = p11[0];
	p11[0] = p22[0];
	p22[0] = tmp;

	p1->bark();
	p2->bark();

	delete p1;
	delete p2;

	return 0;
}

输出:

加菲猫bark: wang wang
二哈 bark: miao miao!
class Base
{
public:
	virtual void show(int i = 10)
	{
		cout << "call Base::show i:" << i << endl;
	}
};

class Derive : public Base
{
public:
	void show(int i = 20)
	{
		cout << "call Derive::show i:" << i << endl;
	}
};

int main()
{
	Base *p = new Derive();
	/*
	push 0Ah -> 函数调用,参数压栈是在编译器就确定好的
	mov eax, dword ptr[p]
	mov ecx, dword ptr[eax]
	call ecx
	*/
	p->show(); //call Derive::show i:10
	//i为基类的默认参数
	delete p;
	return 0;
}
class Base
{
public:
	virtual void show()
	{
		cout << "call Base::show "<< endl;
	}
};

class Derive : public Base
{
//private
private:
	void show()
	{
		cout << "call Derive::show" << endl;
	}
};

int main()
{
	Base *p = new Derive();
	/*
	成员方法能不能调用,就是说方法的访问权限是不是public的,是在编译阶段就需要
	确定好的
	编译阶段:Base::show
	*/
	p->show();//最终能调用到Derive::show,是在运行时期才确定的
	delete p;
	return 0;
}
class Base
{
public:
	Base()
	{
		/*
		push ebp
		mov ebp, esp
		sub esp, 4Ch
		rep stos esp<->ebp 0xCCCCCCCC (windows VS GCC/G++)
		vfptr <- &Base::vftable
		*/
		cout << "call Base()" << endl;
		clear();
	}
	void clear() { memset(this, 0, sizeof(*this)); }
	virtual void show()
	{
		cout << "call Base::show "<< endl;
	}
};

class Derive : public Base
{
public:
	Derive()
	{
		cout << "call Derive()" << endl;
	}
	void show()
	{
		cout << "call Derive::show" << endl;
	}
};

int main()
{
	Base *pb1 = new Base();
	pb1->show();
	delete pb1;

	Base *pb2 = new Derive();
	pb2->show();
	delete pb2;

	return 0;
}
  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

高二的笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值