学习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");
}
可以看出,重载函数在调用时要严格匹配到参数个数,且在函数定义时不能给定初值。而缺省参数函数在调用时比较灵活,既可以给定初值,还不用限定参数个数。当时想这样的话为什么还有重载去实现呢?呵呵,只是这种应用场景罢了,重载在其他场合大有用处。
再记录下析构函数,析构主要是在最后释放对象的分配空间。析构和构造是对应的,在调用时有多少个对象系统就默认产生多少个析构函数,且运行析构的顺序和构造函数定义的顺序相反,析构函数是不存在重载的概念。