建構子(Constructor)
建構子為類別中的特殊方法, 具有如下的特性
1. 當物件生成時, 會自動執行. 通常用來作初始化物件. 此方法因會自動執行, 故一定是public(也有例外)
2. 其方法名稱和類別名稱一模一樣。
3. 而且沒有傳回值, 甚至連void都沒有.
4. 如果沒有宣告自訂建構子, 編譯器會自動建立預設建構子.
5. 如果有自行定義建構子,則不會自動產生預設建構子, 需自行撰寫
class Car{
private:
int speed;
public:
/*
Car(){
speed=0;
}
*/
Car(int speed){
this->speed=speed;
}
int getSpeed(){
return speed;
}
};
int main(){
// Car *car1=new Car();此行會在編譯時指出錯誤
Car *car2=new Car(50);
printf("Car speed : %d\n", car->getSpeed(50));
}
解建構子(Destructor)
當物件結束時,通常需要清除記憶体,關閉檔案,就需此解建構子
public:
~Car(){
}
如下範例說明
class Car{
private:
int speed;
public:
Car(int speed){
this->speed=speed;
}
int getSpeed(){
return speed;
}
~Car(){
printf("執行解建構子\n");
}
};
int main(){
Car *car1=new Car(50);
printf("Car speed : %d\n", car1->getSpeed());
delete car1;
}
static
static 方法及變數,不需要建立物件就可以使用,不可操作任何物件變數。當物件消失後,此static依然存在。
class MyMath{
public:
static int factorial(int x, int y){
if (x>y || x<0)return -1;
if (x==0)x=1;
if(x<y)return x*factorial(x+1, y);
else return y;
}
};
int main(){
printf("%d\n", Math::factorial(0,5));
system("pause");
return 0;
}
static 方法不可使用非static 方法或變數
class Test{
public:
int speed=10;
static int test{
return speed;//此行會出錯,因test在程式一執行就存在,但speed需到new才會出現
}
};
