007.C++建構函式
阿新 • • 發佈:2018-12-14
1.一個引例
//class head class complex //class body {} { public: complex(double r=0, double i) :re(r), im(i) {}//建構函式 complex& operator += (const complex&); double real() const { return re; }//獲取實部的函式 double imag() const { return im; }//獲取虛部的函式 private: doublere, im; friend complex& __doapl(complex*, const complex&); };
2.建構函式的特點
- 建構函式名稱與類名相同;
- 沒有任何返回值型別,因為不需要;
- 可以用初始列的方式定義預設實參;
3.初始列定義建構函式預設實參
注意,一般的函式也是可以定義預設實參的,以下就是一個通用的方式
complex (double r = 0, dobule i = 0) { re = r; im = i;} //賦值語句
然而,上面的方式效率不是最高的。一般地,資料處理有兩個階段,即“初始化”和“賦值”,上面的方式直接跳過了階段一,效率偏低。
對於建構函式,可以使用初始列(初值列)的方式來定義預設實參,充分利用這種特殊性。
complex ( double r = 0, double i = 0) : re(r), im(i) //初值列 {}
4.建構函式的呼叫
4.1設定了預設實參
#include <iostream> using namespace std; class complex //class body {} { public: complex(double r = 0, double i = 0) :re(r), im(i) {}//建構函式 complex& operator += (const complex&); double real() const { return re; }//獲取實部的函式 double imag() const { return im; }//獲取虛部的函式 private: double re, im; friend complex& __doapl(complex*, const complex&); }; int main() { complex c1(2, 1); //方法一:傳遞兩個引數 complex c2; //方法二:不傳遞引數,因為有設定預設引數 cout << "c1=" << c1.real() << "+" << c1.imag() << "i" << endl; cout << "c2=" << c2.real() << "+" << c2.imag() << "i" << endl; return 0; }
4.2 未設定預設實參
此時,只支援方法一呼叫,不支援方法二呼叫。