【C++】構造函數和析構函數

#include <iostream>
using namespace std;

class test{
private:
int a; //放在私有中,有助於保護,通過set和get方法得到其值
public:
test(){ //無參構造函數
a = 10;
}

test(int a){ //有參構造函數
this->a = a;
}
test(const test &obj){ //有參構造函數  完成對象的初始化
cout << "我也是構造函數!"<< endl;
}

~test(){ //結束時自動調用
cout << "我是析構函數!"<< endl;
getchar(); //測試
}

int geta(){
return a;
}


};
int main()
{
test t1(20); //構造函數自動調用
test t2();
test t3(t1);
cout << t1.geta() << endl;
test t4 = 30;
cout << t4.geta() << endl;
test t5 = test(40); //手動調用構造函數
cout << t5.geta() << endl;
getchar();
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章