在例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
请按任意键继续. . .


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值