學習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");
}
可以看出,重載函數在調用時要嚴格匹配到參數個數,且在函數定義時不能給定初值。而缺省參數函數在調用時比較靈活,既可以給定初值,還不用限定參數個數。當時想這樣的話爲什麼還有重載去實現呢?呵呵,只是這種應用場景罷了,重載在其他場合大有用處。
再記錄下析構函數,析構主要是在最後釋放對象的分配空間。析構和構造是對應的,在調用時有多少個對象系統就默認產生多少個析構函數,且運行析構的順序和構造函數定義的順序相反,析構函數是不存在重載的概念。