1. 程式人生 > >初學程式設計C++之動態多型

初學程式設計C++之動態多型

程式碼示例:

#include<iostream>
#include<stdlib.h>
#include"Shape.h"
#include"Circle.h"
#include"Rect.h"
using namespace std;

/**
  動態多型、虛擬函式
  要求:
     1、定義Shape類: 成員函式:calcArea()、建構函式、解構函式
	 2、定義Rect類:  成員函式:calcArea()、建構函式、解構函式
	                  資料成員:m_dWidth、m_dHeight
	 3、定義Circle類:成員函式:calcArea()、建構函式、解構函式
	                  資料成員:m_dR
	*/

#ifndef SHAPE_H
#define SHAPE_H

#include<iostream>

using namespace std;

class Shape
{
public:
	Shape();
	virtual ~Shape();
	virtual double calcArea();

};

#endif

#include“Shape.h”
Shape::Shape()
{
	cout<<"Shape()"<<endl;
}
Shape::~Shape()
{
	cout<<"~Shape()"<<endl;
}
double Shape::calcArea()
{
	cout<<"Shape-->clacArea()"<<endl;
	return 0;
}

#ifndef RECT_H
#define RECT_H

class Rect:public Shape
{
public:
	Rect(double width,double height);
	~Rect();
	virtual double caleArea();
protected:
	double m_dWidth;
	double m_dHeight;
};
#endif

Rect::Rect(double width,double height)
{
	cout<<"Rect()"<<endl;
	m_dHeight=height;
	m_dWidth=width;

}
Rect::~Rect()
{
	cout<<"~Rect()"<<endl;
}
double Rect::caleArea()
{
	cout<<" Rect-->caleArea()"<<endl;
	return m_dWidth*m_dHeight;
}

#ifndef CIRCLE_H
#define CIRCLE_H

#include"Shape.h"
class Circle:public Shape
{
public:
	Circle(double m_dr);
	~Circle();
	virtual double calcArea();
protected:
	double m_dR;
};
#endif

Circle::Circle(double m_dr)
{
	cout<<"Circle ()"<<endl;
	m_dR=m_dr;
}
Circle::~Circle()
{
	cout<<"~Circle()"<<endl;
}
double Circle::calcArea()
{
	cout<<"Circle-->calcArea()"<<endl;
	return 3.14*m_dR*m_dR;
}

int main(void)
{
	Shape*shape1=new Rect(3,6);
	Shape*shape2=new Circle(5);
	shape1->calcArea();
	shape2->calcArea();
	
	delete shape1;
	shape1=NULL;
	delete shape2;
	shape2=NULL;
	system("pause");
	return 0;
}

列印結果:
在這裡插入圖片描述