下面隨筆將給出C++多檔案結構和預編譯命令細節,
多檔案結構和編譯預處理命令
c++程式的一般組織結構
一個工程可以劃分多個源檔案
類宣告檔案(.h檔案)
類實作檔案(.cpp檔案)
類的使用檔案(main()所在.cpp檔案)
利用工程來組合各個檔案
多檔案工程舉例

1 //檔案1,類的定義,Point.h 2 3 class Point { //類的定義 4 5 public: //外部介面 6 7 Point(int x = 0, int y = 0) : x(x), y(y) { count++; } 8 9 Point(const Point &p); 10 11 ~Point() { count--; } 12 13 int getX() const { return x; } 14 15 int getY() const { return y; } 16 17 static void showCount(); //靜態函式成員 18 19 private: //私有資料成員 20 21 int x, y; 22 23 static int count; //靜態資料成員 24 25 };
1 //檔案2,類的實作,Point.cpp 2 3 #include "Point.h" 4 5 #include <iostream> 6 7 using namespace std; 8 9 10 11 int Point::count = 0; //使用類名初始化靜態資料成員 12 13 14 15 Point::Point(const Point &p) : x(p.x), y(p.y) { 16 17 count++; 18 19 } 20 21 22 23 void Point::showCount() { 24 25 cout << " Object count = " << count << endl; 26 27 }
1 //檔案3,主函式,5_10.cpp 2 3 #include "Point.h" 4 5 #include <iostream> 6 7 using namespace std; 8 9 10 11 int main() { 12 13 Point a(4, 5); //定義物件a,其建構式使count增1 14 15 cout <<"Point A: "<<a.getX()<<", "<<a.getY(); 16 17 Point::showCount(); //輸出物件個數 18 19 Point b(a); //定義物件b,其建構式回使count增1 20 21 cout <<"Point B: "<<b.getX()<<", "<<b.getY(); 22 23 Point::showCount(); //輸出物件個數 24 25 return 0; 26 27 }
條件編譯指令——#if 和 #endif
#if 常量運算式
//當“ 常量運算式”非零時編譯
程式正文
#endif
......
條件編譯指令——#else
#if 常量運算式
//當“ 常量運算式”非零時編譯
程式正文1
#else
//當“ 常量運算式”為零時編譯
程式正文2
#endif
條件編譯指令——#elif
#if 常量運算式1
程式正文1 //當“ 常量運算式1”非零時編譯
#elif 常量運算式2
程式正文2 //當“ 常量運算式2”非零時編譯
#else
程式正文3 //其他情況下編譯
#endif
條件編譯指令
#ifdef 識別符號
程式段1
#else
程式段2
#endif
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/261596.html
標籤:C++
上一篇:C++共享資料保護機制
