C++程式設計中類CALSS的編寫(一):不含指標資料的類
阿新 • • 發佈:2019-02-07
首先,在我理解當中,C++程式設計中的類可以分為兩種型別,第一種是包含指標的,另一種則是不包含的,不包含指標的類,其中private裡填寫自己的資料,這時候其中的資料型別比如int,double,float等等型別都是標準庫裡面已經寫好的,也自動為我們分配了記憶體,不用去考慮記憶體分配問題,也就不會有別名的問題產生,當然此時,解構函式也不用編寫了,在程式結束的時候,自動析構。此時主要編寫的程式有建構函式,運算子過載和普通的成員函式,對於拷貝構造這裡做一個解釋就是:我們採用預設的拷貝建構函式,因為其效率足夠,也不會有淺拷貝現象,可以不予編寫。
接著以一個標準庫裡的COMPLEX類來談談自己對於這部分的理解,先給出自己模仿編寫的complex.h,取了標準庫裡的其中一部分:
#ifndef COMPLEX_H #define COMPLEX_H //防衛式宣告,防止重複定義 #include <iostream> //using namespace std; //主要是針對輸出流的運算子過載使用 class complex{ public: complex(double r = 0,double i = 0):re(r),im(i){} //記住 初始化列表非常重要,採用賦值會產生效率低下,建立物件時先初始化再賦值,不必浪費初始化這個時間 ~complex(){} complex& operator += (const complex& rhs); double real() const{ return re;} double imag() const{ return im;} //為了封裝性,提供獲得資料的介面,加上const是為了防止如果我建立一個const物件,但是呼叫的是非const函式,//編譯器就不樂意了,你會不會改變資料不知道,所以不改變資料的函式必須要加上const complex operator + (const complex& rhs) { //返回值之所以不為引用,是為了防止懸掛,如果使用引用,+號運算肯定產生一個local,當返回這個local的引用//時,在函式結束的時候會使得local物件被析構,這時候傳遞出來的地址已經非法 return complex(this->re + rhs.re, this->im + rhs.im); } complex operator + (double x) { //為什麼在這裡寫了+的運算子過載,還要在非成員函式寫,問:呼叫者如果是非複數怎麼辦,放成員函式裡就不能做到 return complex(x+this->re,this->im); } private: double re,im; friend complex& __doapl(complex* ths,const complex& rhs); }; inline complex& __doapl(complex* ths,const complex& rhs){ //因為是friend 可以訪問 ths->re += rhs.re; ths->im += rhs.im; return *ths; } inline complex& complex::operator += (const complex& rhs){ return __doapl(this,rhs); } inline complex operator + (const double x,const complex& rhs){ return complex(x+rhs.real(),rhs.imag()); } inline complex operator + (const complex& x) { return x; } inline complex operator - (const complex& x){ return complex(-x.real(),-x.imag()); } inline complex conj(const complex& rhs){ return complex(rhs.real(),-rhs.imag()); }; std::ostream& operator << (std::ostream& os,const complex& rhs){ //用了ostream的全名,如果沒有,編譯器無法知道這個os到底在哪 return os << '(' << rhs.real() << ',' << rhs.imag() << ')'; } #endif