重载构造函数、缺省参数构造函数及析构函数

学习C++过程中,把学习到的点滴做些记录吧

碰到两个功能实现很相近的构造函数:重载和缺省。虽然功能实现差不多,但还是有些区别:

//重载函数的功能实现
class complex
{
private:
	double real;
	double imag;
public:
	//构造函数
	complex(double r,double i)
	{
		real=r;
		imag=i;
	}
	//构成重载函数
	complex()
	{
		real=2.0;
		imag=2.0;
	}
	complex(double m)
	{
		real=4.0;
		imag=m;
	}
	//析构函数
	~complex()
	{
		cout<<"the space has released!\n";
	}
	//得到复数的实部和虚部
    double realcomplex()
	{
		return real;
	}
	double imagcomplex()
	{
		return imag;
	}
	//计算模
	double abscomplex()
	{
		double t;
		t=real*real+imag*imag;
		return sqrt(t);
	}
};  

void main()
{
	complex a(1.12,2.13);
	complex b;
	complex c(2.45);
	
	cout<<"real of a:"<<a.realcomplex()<<"\n"<<"imag of a:"<<a.imagcomplex()<<"\n"
		<<"abs of a:"<<a.abscomplex()<<endl;
	cout<<"real of b:"<<b.realcomplex()<<"\n"<<"imag of b:"<<b.imagcomplex()<<"\n"
		<<"abs of b:"<<b.abscomplex()<<endl;
	cout<<"real of c:"<<c.realcomplex()<<"\n"<<"imag of c:"<<c.imagcomplex()<<"\n"
		<<"abs of c:"<<c.abscomplex()<<endl;
	system("pause");
}  
//缺省参数构造函数功能实现

#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;

class complex
{
private:
	double real;
	double imag;
public:
	//构造函数
	complex(double r=1.0,double i=1.0)
	{
		real=r;
		imag=i;
	}
	//析构函数
	~complex()
	{
		cout<<"the space has released!\n";
	}
	//得到复数的实部和虚部
    double realcomplex()
	{
		return real;
	}
	double imagcomplex()
	{
		return imag;
	}
	//计算模
	double abscomplex()
	{
		double t;
		t=real*real+imag*imag;
		return sqrt(t);
	}
};  //再次强调定义类时要“;”

void main()
{
	complex a(1.12,2.13);
	complex b;
	complex c(2.45);
	
	cout<<"real of a:"<<a.realcomplex()<<"\n"<<"imag of a:"<<a.imagcomplex()<<"\n"
		<<"abs of a:"<<a.abscomplex()<<endl;
	cout<<"real of b:"<<b.realcomplex()<<"\n"<<"imag of b:"<<b.imagcomplex()<<"\n"
		<<"abs of b:"<<b.abscomplex()<<endl;
	cout<<"real of c:"<<c.realcomplex()<<"\n"<<"imag of c:"<<c.imagcomplex()<<"\n"
		<<"abs of c:"<<c.abscomplex()<<endl;
	system("pause");
}  

可以看出,重载函数在调用时要严格匹配到参数个数,且在函数定义时不能给定初值。而缺省参数函数在调用时比较灵活,既可以给定初值,还不用限定参数个数。当时想这样的话为什么还有重载去实现呢?呵呵,只是这种应用场景罢了,重载在其他场合大有用处。

再记录下析构函数,析构主要是在最后释放对象的分配空间。析构和构造是对应的,在调用时有多少个对象系统就默认产生多少个析构函数,且运行析构的顺序和构造函数定义的顺序相反,析构函数是不存在重载的概念。



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值