構造函數可以有多個(重載),而析構函數只有一個(不能對析構函數進行重載)。
如果忘記實現析構函數,編譯器會自動生成一個僞析構函數(空函數),從下面代碼,可以看出析構函數的使用及調用順序。
/*Human.h*/
#include <string>
class Human
{
private:
std::string* name;//爲了演示析構函數的作用
/*public類外可訪問*/
public:
void getPersonName();
Human(std::string input);
~Human();
};
#include <iostream>
#include <string>
#include "Human.h"
/*構造函數(創建對象時被調用)*/
Human::Human(std::string input)
{
std::cout << "1 call Human()" << std::endl;
name = new std::string(input); //在構造函數中用new在堆上創建變量,在析構函數中釋放
}
/*析構函數(對象被銷燬時被調用,類只有一個析構函數*/
Human::~Human()
{
delete name; //在析構函數裏面釋放
std::cout << "2 call ~Human()" << std::endl;
}
/*類方法的實現*/
void Human::getPersonName()
{
std::cout << "3 get name is " << *name << std::endl;
}
#include <iostream>
#include "Human.h"
int main()
{
Human man("ONE"); //跟int一樣,使用數據類型Hunam實例化對象,類內的成員和方法,只有實例化對象後才能被使用
man.getPersonName();
return 0;
}
輸出:
1 call Human()
3 get name is ONE
2 call ~Human()