1. 程式人生 > >在例12.3的基礎上作以下修改,並作必要的討論。

在例12.3的基礎上作以下修改,並作必要的討論。

 在例12.3的基礎上作以下修改,並作必要的討論。

(1) 把建構函式修改為帶引數的函式,在建立物件時初始化。

(2) 先不將解構函式宣告為virtual,在main函式中另設一個指向Circle類物件的指標變數,使它指向grad1。執行程式,分析結果。

(3) 不作第(2)點的修改而將解構函式宣告為virtual,執行程式,分析結果。

(1) 把建構函式修改為帶引數的函式,在建立物件時初始化。

#include<iostream>
using namespace std;
class Point
{
	public:
		Point(int a,int b){
			a=x;
			b=y;
		}
	
    ~Point()
	{
		cout<<"executing Point destructor"<<endl;
	}
	private:
		int x;
		int y;
};
class Circle:public Point
{
	public:
		Circle(int a,int b,int c ):Point(a,b),radus(c){
		}
		~Circle()
		{
			cout<<"executing Circle destructor"<<endl;
		}
	private:
		int radus;
};
int main()
{
	Point *p=new Circle(2.5,1.8,4.5);
	delete p;
	return 0;
}
executing Point destructor


--------------------------------
Process exited after 1.446 seconds with return value 0
請按任意鍵繼續. . .

(2) 先不將解構函式宣告為virtual,在main函式中另設一個指向Circle類物件的指標變數,使它指向grad1。執行程式,分析結果。

int main()
{
	Point *p=new Circle(2.5,1.8,4.5);
	Circle *pt=new Circle(2.5,1.8,4.5);
	delete pt;
	return 0;
}
executing Circle destructor
executing Point destructor


--------------------------------
Process exited after 0.02144 seconds with return value 0
請按任意鍵繼續. . .


(3) 不作第(2)點的修改而將解構函式宣告為virtual,執行程式,分析結果。

#include<iostream>
using namespace std;
class Point
{
	public:
		Point(int a,int b){
			a=x;
			b=y;
		}
	
   virtual ~Point()
	{
		cout<<"executing Point destructor"<<endl;
	}
	private:
		int x;
		int y;
};
class Circle:public Point
{
	public:
		Circle(int a,int b,int c ):Point(a,b),radus(c){
		}
		~Circle()
		{
			cout<<"executing Circle destructor"<<endl;
		}
	private:
		int radus;
};
int main()
{
	Point *p=new Circle(2.5,1.8,4.5);
	delete p;
	return 0;
}
executing Circle destructor
executing Point destructor


--------------------------------
Process exited after 0.5465 seconds with return value 0
請按任意鍵繼續. . .