【C++】:继承、虚函数、多态

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bqw18744018044/article/details/88628193
  • 继承

继承允许依据一个类来定义另一个类,这样可以提供代码重用率等。下面是一个Rectangle继承Shape类的例子:

//基类
class Shape
{
protected:
	int width;
	int height;
public:
	void setWidth(int w){
		width = w;
	}
	void setHeight(int h){
		height = h;
	}
}
//派生类
class Rectangle:public Shape{
public:
	int getArea(){
		return width*height;
	}
}

多重继承:一个子类继承自多个父类;

 

  • 多态、虚函数与重写

  • 多态:在基类的函数前面加上virtual关键字,在派生类中重写该函数,运行时将会根据对象的实际类型来调用相应的函数。如果对象是派生类,就调用派生类的函数;如果对象是基类,那么就调用基类的函数。
//基类
class Shape{
protected:
	int width,height;
public:
	Shape(int w=0, int h=0){
		width = w;
		height = h;
	}
	virtual int area(){//虚函数
		cout<<"Parent class area:"<<endl;
		return 0;
	}
};

class Rectangle:public Shape{
public:
	Rectangle(int w=0,int h=0):Shape(w,h){}
	int area(){//重写基类的area函数
		cout<<"Rectangle class area:"<<endl;
		return width*height;
	}
};

class Triangle:public Shape{
public:
	Triangle(int w=0,int h=0):Shape(w,h){}
	int area(){//重写基类的area函数
		cout<<"Triangle class area:"<<endl;
		return (width*height)/2;
	}
};

int main()
{
	Shape* shape;//基类指针
	Rectangle rec(10,7);
	Triangle tri(10,5);
	
	//多态
	shape = &rec;//基类指针指向Rectangle对象
	shape->area();//调用Rectangle对象的area()方法
	
	shape = &tri;//基类指针指向Triangle对象
	shape->area();//调用Triangle对象的area()方法
	
	return 0;
}

 

  • 虚函数

虚函数是在基类中使用virtual声明的函数。在派生类中重写基类中的虚函数,会告诉编译器不要静态链接到该函数,而是要在程序中由对象的类型决定要使用的函数,这种方式被称为动态链接或后期绑定。

  • 纯虚函数

虚函数在基类中可以有实现,如果希望虚函数在基类中不给出实现,而且完全由派生了给出,那么可以使用纯虚函数。

class Shape{
protected:
	int width,height;
public:
	Shape(int w=0, int h=0){
		width = w;
		height = h;
	}
	virtual int area()=0;//纯虚函数
};

猜你喜欢

转载自blog.csdn.net/bqw18744018044/article/details/88628193