Appearance
更多物件中的函數
除了這種最直觀的運用,這種函數還可以與很多內建的運算結合,或是進行初始化,讓物件使用變得很直觀。
- 初始化
- 解構函數
- 結合運算子
初始化
在之前的 struct,每一個數值必須手動給予才能使用,這十分的不方便。
c
// C
struct Person {
int weight, height;
float BMI;
};
struct Person p = {a, b, a/((float)b*b/1e4)};C
// C++
class Person {
public:
int height, weight;
float BMI;
Person(int w, int h) {
height = h;
weight = w;
float h_meter = h * 0.01;
BMI = w / (h_meter * h_meter);
}
};這樣子只要使用兩個參數,物件就會自己推敲出第三個參數,儘管這個例子並沒有顯著差異,但當物件變得複雜時,冗長的初始化就會造成負擔。
解構函數
之前在 struct 中,有介紹過把 pointer 放到物件中容易造成問題,因此可以使用 解構函數 統一處理這些記憶體。
C
class Example{
public:
int *ptr;
Example() {
ptr = new int(0);
if (!ptr) throw("allocation failed"); // C++ 的報錯
}
~Example() {
cout << "解構子被呼叫\n";
delete ptr;
}
};
Example *a = new Example;
delete a; // call ~Example