原创 linux下c++ lesson10 多态

28 篇文章 0 订阅

1-问题引出.cpp

#include <iostream>

using namespace std;

class Parent
{
public:
	void show()
	{
		cout << "this is parent"  << endl;
	}
};

class Child : public Parent
{
public:
	void show()
	{
		cout << "this is Child" << endl;
	}
};

int main()
{
	Child c;
	Parent p;

	p = c;

	Parent *p1 = new Child;   //基类指针指向派生类对象
	p1->show();   //静态联编:编译器根据p1的类型(Parent *)调用Parent里面的show函数

	return 0;
}

2-多态概念.cpp

#include <iostream>

using namespace std;

class Parent
{
public:
	virtual void show()    //被virtual修饰的函数叫虚函数
	{
		cout << "this is parent"  << endl;
	}
};

class Child : public Parent   //1、要有继承
{
public:
	void show()    //2、要有虚函数重写(发生在不同的作用域中,函数原型相同)
	{
		cout << "this is Child" << endl;
	}
};

int main()
{
	Child c;
	Parent p;

	p = c;

	Parent *p1 = new Child;   //3、基类指针指向派生类对象
	p1->show();   //动态联编:运行的时候才能知道p1指向什么对象
	delete p1;
	p1 = new Parent;    //基类指针指向基类对象
	p1->show();     //相同的语句有不同的执行结果(多态:多种形态)
	delete p1;

	return 0;
}

3-多态原理.cpp

#include <iostream>

using namespace std;

class Parent
{
public:
	int a;
	virtual void show()
	{
		cout << "thsi is parent" << endl;
	}
};

class Child : public Parent
{
public:
	virtual void show()
	{
		cout << "this is Child" << endl;
	}
};

int main()
{
	Parent p;
	Child c;

	cout << sizeof(c) << endl;
	cout << sizeof(p) << endl;
	cout << "Parent对象的起始地址 " << &p << endl;
	cout << "成员变量a的起始地址 "  << &p.a << endl;

	Parent *p = new Child;
	p->show();   //通过指针找到对象,通过对象前8个字节找到虚函数表,通过虚函数表找到对应的函数,调用函数(效率低)
				//不要将所有函数都声明成虚函数

	delete p;
	p = new Parent;
	p->show();


	return 0;
}

4-虚析构函数.cpp

#include <iostream>

using namespace std;

class Parent
{
public:
	Parent()
	{
		cout << "Parent构造函数" << endl;
	}
	virtual void show()    //被virtual修饰的函数叫虚函数
	{
		cout << "this is parent"  << endl;
	}

	virtual ~Parent()
	{
		cout << "Parent析构函数" << endl;
	}
};

class Child : public Parent   //1、要有继承
{
public:
	Child()
	{
		cout << "Child构造函数" << endl;
	}
	void show()    //2、要有虚函数重写(发生在不同的作用域中,函数原型相同)
	{
		cout << "this is Child" << endl;
	}
	~Child()
	{
		cout << "Child析构函数" << endl;
	}
};

int main()
{
	//Child c;
	//Parent p;

	//p = c;

	Parent *p1 = new Child;   //3、基类指针指向派生类对象
	p1->show();   //动态联编:运行的时候才能知道p1指向什么对象
	delete p1;    //释放派生类对象  虚析构函数:通过基类指针释放派生类对象

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值