返回列表 回復 發帖

VC++2008程式碼寫作方式的選擇?

我在讀一本書,書名叫『掌握VC++關鍵技術』,書中提到使用『茴字的N種寫法』:
1. 使用Windows API (WriteFile, ReadFile)
2. 使用標準C++函式庫 (ofstream, ifstream)
3. 使用CRT (fprintf, fscanf)
4. 使用CRT函式庫的寬字串版本 (fwprintf, fwscanf)
5. 使用CRT函式庫的安全版本 (fwprintf_s, fwscanf_s)
6. 使用MFC/ATL (CFile::Write, CFile::Read)
7. 使用C++/CLI (StreamWriter, StreamReader)

各種寫法介紹完之後,作者提到『該採用哪一種寫法』:
。。。因此,本書中我們儘量只介紹本機C++的用法,在本機C++語言中,如果同時又存在著幾種技術實現方法,那麼我們給讀者的建議是:優先採用MFC和Windows API,其次再使用標準C++的類別和CRT函式庫。

書還沒看完,但是,到此,我還是搞不清楚哪些是MFC的東東,哪些又是標準C++函式庫。只有Windows API是看到就知道是這種的而已!

分不清楚什麼是什麼,要怎麼選擇呢?!這個問題或許多學點就會知道,不過,就先把它列在這裡,讓有心得的朋友們給點建議!


底下的問題才是這裡真正要問的。下面的一段程式碼是建立在『Win32主控台程式』並設定支援『MFC/ATL』下寫的。其中,前後各有兩段我用『這是第一種寫法(已被//標示起來當做註解)』及『這是第二種寫法』分隔開來。想知道的是,各位已有寫VC++的朋友們的經驗裡,會選擇哪一種方式來寫?

乍看下,第一種寫法好像是直接用指標操作,是不是在效能方面會較第二種寫法好?!
  1. // 掌握VCPP 3-3.cpp : 定義主控台應用程式的進入點。
  2. //
  3. #include "stdafx.h"
  4. #include "掌握VCPP 3-3.h"

  5. //這是第一種寫法
  6. //#include <cstdio>
  7. //#include <cstring>
  8. //這是第二種寫法
  9. #include <iostream>
  10. #include <string>

  11. #ifdef _DEBUG
  12. #define new DEBUG_NEW
  13. #endif

  14. // 僅有的一個應用程式物件
  15. CWinApp theApp;
  16. using namespace std;
  17. int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
  18. {
  19. int nRetCode = 0;
  20. // 初始化 MFC 並於失敗時列印錯誤
  21. if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
  22. {
  23.   // TODO: 配合您的需要變更錯誤碼
  24.   _tprintf(_T("嚴重錯誤: MFC 初始化失敗\n"));
  25.   nRetCode = 1;
  26. }
  27. else
  28. {
  29.   // TODO: 在此撰寫應用程式行為的程式碼。

  30.   //這是第一種寫法
  31.   //char src[] = "Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.";
  32.   //char key[] = "aeiou";
  33.   //char *cp;
  34.   //printf("%s\r\n",src);
  35.   //printf("母音子母: ");
  36.   //cp = strpbrk(src,key);
  37.   //int i = 0;
  38.   //while(cp != NULL)
  39.   //{
  40.   // i++;
  41.   // printf("%c ",*cp);
  42.   // cp = strpbrk(cp+1,key);
  43.   //}
  44.   //printf("\r\n共有%d個母音\r\n",i);
  45.   //這是第二種寫法
  46.   string src ("Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.");
  47.   cout << src << endl;
  48.   size_t cp;
  49.   cp = src.find_first_of("aeiou");
  50.   int i = 0;
  51.   while (cp != string::npos)
  52.   {
  53.    cout << src.at(cp) << " ";
  54.    cp = src.find_first_of("aeiou",cp+1);
  55.    i++;
  56.   }
  57.   cout << endl << "共有" << i << "個母音" << endl;

  58. }
  59. return nRetCode;
  60. }
複製代碼
純VC++菜鳥,所問問題可能程度太低,尚請見諒!
乍看下,第一種寫法好像是直接用指標操作,是不是在效能方面會較第二種寫法好?!
Kevin 發表於 2010-4-9 18:42
這裡,我有點白痴,兩種寫法的效率,跟指標根本無關。

有關係的是,第一種寫法使用cstring定義的strpbrk函式來找指定字元在源字串中的指標位置,而第二種則是用string類別的find_first_of函式來找指定字元的第一個匹配位置。

至於哪種寫法比較好,書中也沒說明。只提到第一種寫法是在古老的C時代裡,各種軟體的程式碼中常會充滿這些函數(cstring中所定義的函數)的呼叫。而第二種寫法則是標準C++所提供的類別。

既然如此,兩組程式碼的效率應該就差不到哪兒去吧!ㄚ哉?!書繼續看下去!
返回列表 回復 發帖