多态和虚函数


#include <iostream>

using namespace std;

class Shape{
	public:
		virtual void area(){
			cout<<"shape"<<endl;
		}
		
};

class Circle:public Shape{
	int radius;
	public:
		Circle(int r){
			radius = r;
		}
		void area(){
			cout<<"area="<<3.14*radius*radius<<endl;
		}
};
	class Rectangle:public Shape{
		int width,height;
		public:
			Rectangle(int width,int height){
				this->width=width;
				this->height= height;
				
			}
			void area(){
				cout<<"area="<<width*height<<endl;
			}
			
	};
	
	
	void GetArea(Shape * p){  //计算任意图形的面积 
		p->area();
	}
	
	/* void GetArea(Shape & p)
	{
		p.area();//引用,打点调用 
	} 
	*/
	
int main(){
	Circle c(1); 
	Rectangle r(4,5);
	GetArea( &c);
	GetArea(&r);
	return 0;
}

多态应满足的三个条件:虚函数、赋值兼容性、指针或引用调用虚函数

1. 虚函数

如果将virtual去掉,就会静态绑定用Shape中的area(),输出两个shape,

如果加上virtual就会给编译器发一个信号:“这个函数可能会被子类重写,你现在不要急着决定调用哪个版本,等程序运行起来再决定。”,这就是动态绑定(也叫晚绑定),也就是我们常说的多态(Polymorphism)。

2. 赋值兼容性

基类指针可以指向派生类地址,派生类指针不可以指向基类地址

基类与指针、向上映射

3. 指针或引用调用虚函数

void GetArea();调用虚函数

纯虚函数

有纯虚函数的类叫做抽象类

抽象类不能创建对象,派生类必须实现纯虚函数的重写,才能变成普通的类。

构造函数与析构函数

析构函数最好定义为虚函数

posted @ 2026-04-19 09:25  叶臧  阅读(16)  评论(0)    收藏  举报