c++0.1-----不包含指針的類~~~知識點大綜合
阿新 • • 發佈:2018-07-01
系統 包含 using endif 頭文件 知識點 ++ #define FN
本篇文章包含知識點有:預編譯,訪問權限,內聯函數,常成員函數,構造函數,運算符重載函數,友元。
以代碼為示範:
文件名:ccompex.h
文件內容:定義一個簡單的復數類。
1 #ifndef __CCOMPLEX__ 2 #define __CCOMPLEX__ 3 #include <iostream> 4 #include <ostream> 5 using namespace std; 6 class complex{ 7 friend complex& __doapl(complex& com1,const complex& com2);8 public: 9 inline const double& real() const {return re;} 10 inline const double& image() const {return im;} 11 inline complex(double r=0.0,double i=0.0):re(r),im(i){} 12 private: 13 double re; 14 double im; 15 }; 16 17 inline complex & __doapl(complex &com1,const complex& com2)18 { 19 com1.re+=com2.re; 20 com1.im+=com2.im; 21 return com1; 22 } 23 24 inline complex & operator+=(complex &com1,const complex& com2) 25 { 26 return __doapl(com1,com2); 27 } 28 29 inline complex operator+(const complex& com1,const complex& com2) 30 { 31 returncomplex(com1.real()+com2.real(),com1.image()+com2.image()); 32 } 33 inline complex operator+(const complex& com1,const double& dou) 34 { 35 return complex(dou+com1.real(),com1.image()); 36 } 37 inline complex operator+(const double& dou,const complex& com1) 38 { 39 return complex(dou+com1.real(),com1.image()); 40 } 41 42 ostream& operator<<(ostream &os,const complex& x) 43 { 44 os<<‘(‘<<x.real()<<‘,‘<<x.image()<<‘)‘<<endl; 45 } 46 47 #endif // __CCOMPLEX__
這47行代碼包含了幾個c++精髓,下面讓我娓娓道來~~~
一.預編譯:#ifndef---#define---#endif 與#include
#ifndef---#define---#endif 代碼在第1,2,47行,功能是避免頭文件重復調用,在編譯的時候合理將代碼替換過來。
頭鐵不信系列:去掉#ifndef---#define---#endif 後,再多次在主文件包含這個頭文件,進行編譯,編譯器給出以下錯誤信息:
error: redefinition of ‘class complex‘
錯誤解析:以上錯誤信息的意思是說對complex類重定義了。也就是說包含多次該文件,若沒有預編譯的功能,錯誤就會出現。
#include代碼在第3,4行,表示引入一些頭文件。
使用方法:系統頭文件用<>包住,同時,不需要加.h後綴哦。例如:#include<iostream>
自定義頭文件用" "包住。例如:#include "ccomplex.h"。
二.訪問權限:
c++0.1-----不包含指針的類~~~知識點大綜合