2017做網(wǎng)站賺錢短視頻平臺推廣方案
構(gòu)造函數(shù)
類的構(gòu)造函數(shù)是類的一種特殊的成員函數(shù),它會在每次創(chuàng)建類的新對象時執(zhí)行。主要用來在創(chuàng)建對象時初始化對象即為對象成員變量賦初始值。
構(gòu)造函數(shù)的名稱與類的名稱是完全相同的,并且不會返回任何類型,也不會返回 void。構(gòu)造函數(shù)可用于為某些成員變量設(shè)置初始值。
****:
#include <iostream>using namespace std;class Line
{public:void setLength( double len );double getLength( void );Line(); // 這是構(gòu)造函數(shù)private:double length;
};// 成員函數(shù)定義,包括構(gòu)造函數(shù)
Line::Line(void)
{cout << "Object is being created" << endl;
}void Line::setLength( double len )
{length = len;
}double Line::getLength( void )
{return length;
}
// 程序的主函數(shù)
int main( )
{Line line;// 設(shè)置長度line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl;return 0;
}//out:
//Object is being created
//Length of line : 6
帶參數(shù)的構(gòu)造函數(shù)
#include <iostream>using namespace std;class Line
{public:void setLength( double len );double getLength( void );Line(double len); // 這是構(gòu)造函數(shù)private:double length;
};// 成員函數(shù)定義,包括構(gòu)造函數(shù)
Line::Line( double len)
{cout << "Object is being created, length = " << len << endl;length = len;
}void Line::setLength( double len )
{length = len;
}double Line::getLength( void )
{return length;
}
// 程序的主函數(shù)
int main( )
{Line line(10.0);// 獲取默認設(shè)置的長度cout << "Length of line : " << line.getLength() <<endl;// 再次設(shè)置長度line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl;return 0;
}
構(gòu)造函數(shù)有以下特點:
1.構(gòu)造函數(shù)的名字必須與類名相同;
2.構(gòu)造函數(shù)可以有任意類型的參數(shù),但不能具有返回類型;
3.定義對象時,編譯系統(tǒng)會自動地調(diào)用構(gòu)造函數(shù);
4.構(gòu)造函數(shù)是特殊的成員函數(shù),函數(shù)體可以在類體內(nèi),也可寫在類體外;
5.構(gòu)造函數(shù)被聲明為公有函數(shù),但它不能像其他成員函數(shù)那樣被顯式調(diào)用,它是在定義對象的同時被調(diào)用的。
析構(gòu)函數(shù)
類的析構(gòu)函數(shù)是類的一種特殊的成員函數(shù),它會在每次刪除所創(chuàng)建的對象時執(zhí)行。
析構(gòu)函數(shù)的名稱與類的名稱是完全相同的,只是在前面加了個波浪號(~)作為前綴,它不會返回任何值,也不能帶有任何參數(shù)。析構(gòu)函數(shù)有助于在跳出程序(比如關(guān)閉文件、釋放內(nèi)存等)前釋放資源。
#include <iostream>using namespace std;class Line
{public:void setLength( double len );double getLength( void );Line(); // 這是構(gòu)造函數(shù)聲明~Line(); // 這是析構(gòu)函數(shù)聲明private:double length;
};// 成員函數(shù)定義,包括構(gòu)造函數(shù)
Line::Line(void)
{cout << "Object is being created" << endl;
}
Line::~Line(void)
{cout << "Object is being deleted" << endl;
}void Line::setLength( double len )
{length = len;
}double Line::getLength( void )
{return length;
}
// 程序的主函數(shù)
int main( )
{Line line;// 設(shè)置長度line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl;return 0;
}
析構(gòu)函數(shù)在下邊3種情況時被調(diào)用:
1. 對象生命周期結(jié)束被銷毀時
2. delete指向?qū)ο蟮闹羔槙r,或者delete指向?qū)ο蟮幕愵愋偷闹羔?#xff0c;而基類析構(gòu)函數(shù)是虛函數(shù)
3. 對象A是對象B的成員,B的析構(gòu)函數(shù)被調(diào)用時,對象A的析構(gòu)函數(shù)也會被調(diào)用