1、The C+ Programming Language,Lecture 1: From C to C+,Brief Introduction & Requirements,Coding Style Requirements - Naming Conventions,Hungarian Notation GlobalPrefixTypePrefix-BaseTag-Name GlobalPrefix C+ member variables start with: m_ Global variables start with: g_ Static data members start with:
2、s_ Classes start with: C Interfaces start with: I Standard Prefix: p A pointer. CHAR* psz; rg An array. DWORD rgType; pp A pointer to a pointer. int* ppTop; h A handle. HANDLE hFile; ref A reference to. char Func(string,Coding Style Requirements - Naming Conventions (cont.),Standard “BaseTag” void -
3、 v int - i BOOL - f UINT - ui BYTE - b CHAR - ch Double - d float - fl WCHAR - wch ULONG - ul LONG - l DWORD - dw HRESULT - hr fn - function sz - NULL str USHORT, SHORT, WORD - w Name Meaningful and Capitalizing every words Example m_pdTopOfStack CTypeLib g_fSwitchForDest s_szStartingURL,Coding Styl
4、e Requirements - Naming Conventions (cont.),Lets have some tries A flag indicates whether a C+ object has been initialized: BOOL m_fInitialized; A Session ID: DWORD dwSessionID; A Pointer to BYTE buffer: BYTE* pbBuffer; A global buffer to store logfile filename: CHAR g_szLogFileMAX_NUM; A pointer to
5、 a global logfile name: CHAR* g_pszLogFile;,Coding Style Requirements - Code Indentation,4 spaces per indent level,Class CExample public:/member functions declarationCexample();Cexample();private:#ifdef _DEBUGvoid TraceValue( int iValue );#endif ;,While (foo) if (NULL = bar)Func1(ad);elseFunc2(bc);F
6、unc3(); ,Braces in Statements,Useful Concepts Review,Reviewing C in C+,int functionA(int iX, int iY); int functionA(int iX, int iY) ; functionA(3,5);,The first is a declaration, the second is a definition (with null statements), the third is an invoking Declaration of a variable or function can appe
7、ar many times, while definition only once iX & iY - parameters, 3 & 5 - arguments,Reviewing C in C+ (cont.),int iX; extern int iX; int functionB(); extern int functionB();,Keyword extern means it is only a declaration, its definition is later or external to this file, asking the compiler not to assi
8、gn memory or generate code extern int functionB() ; /-invalid,Reviewing C in C+ (cont.),int funcA() static int iX = 0; ,iX is a “local global variable” to the file Its scope is only in this file,Function can “remember ” iX between calls But iX is unavailable outside the function, its scope is in thi
9、s function,static int iX = 0; int funcA() ,Reviewing C in C+ (cont.),int iX = 1024, iY = 4096; int ,Reference rX could be regarded as an alias or another name of iX Could rX represent iY later? - No! pi = /-Only a pointer could do that,Reviewing C in C+ (cont.),int Swap(int iX, int iY); int Swap(int
10、* pX, int* pY); int Swap(int ,The first two are passing by value, the last is passing by reference The first could not modify the value of arguments outside of Swap, while the last two could,Reviewing C in C+ (cont.),3 Reasons to use passing by reference: To modify the objects that passed in the fun
11、ction To avoid the cost of copying large objects To have more than one return values,struct Matrix double a1000010000 ;int f1(Matrix m); int f2(Matrix,bool add_even(int a, int b, int ,Reviewing C in C+ (cont.),The inner mechanism of reference and pointer may be similar, but they are quite different
12、in usage Using Reference when you find It always represents a non-null object And it will not represent any other objects Using Pointer otherwise Pointer could be re-assigned values, while reference could not,Reviewing C in C+ (cont.),int f(int const is also recommended to replace the #define macro,
13、 for the visibility in symbol table during compiling,Reviewing C in C+ (cont.),Overview of the const const int*p =,Reviewing C in C+ (cont.),class CExap class CExap public: public:int m_iX; int m_iX; ; ; CExap v; CExap* v;,v.m_iX = 0; v-m_iX = 0;,. is after an object, - is after a pointer (or iterat
14、or),Reviewing C in C+ (cont.),int main(int argc, char* argv) ;argc passes the number of elements in the argv array, argv are the character sub-sequences separated by spaces from the command line argv 0 is the path and program name, the real arguments start from argv 1 ,Lets compare these,#include vo
15、id main() int j;int v 5 = 1,2,3,4,5;for (j = 0; j 5; j+)printf(“%dn”, v j );,#include #include using namespace std; int main() vector v;for (int j = 0; j 5; j+)v.push_back(j + 1);for (int j = 0; j v.size(); j+)cout v j endl;return 0; ,C Style C+ Style,From C to C+,Say Goodbye To Our Old Friends, , W
16、e prefer the standard C+ library , , scanf(), printf(), fprintf(), We prefer the streaming operators cin , cout , File , malloc(), realloc(), free(), We prefer the C+ operators new & delete, to ensure the calling of constructors and destructors,Namespace,Wrap the library to avoid name collision in g
17、lobal scope, a better way than prefixesint abc_NumOfInstances = 0; namespace abcint abc_Create(int InstNo); int NumOfInstances = 0;int Create(int InstNo); std is the namespace wrapping all standard C+ libraries,Namespace(cont.),3 ways to use namespace Use prefix style to specify every time void f1()
18、 abc:Create(NumOfInstances);abc:NumOfInstances+ Import one symbol to current scope void f2() using abc:NumOfInstances; Create(NumOfInstances); /Error! Only NumOfInstances is visible, Create not importedNumOfInstances+; /OK Import all symbols in a namespace to current scope using directive void f3()
19、using namespace abc; Create(NumOfInstances); /OKNumOfInstances+; /OK ,Namespace(cont.),But we suggest the using directive form to expose all names in standard libraries using namespace std;,Vectors,Lots of legacy codes use array We recommend using the class template Features: A sequential container
20、Can use index to access Be self-aware of size Self-manage memory and increase on demand Frequent used member functions & operators: push_back(), pop_back(), size(), clear(), ,string class,The string class library #include string s; Important ops and member functions: =, +=, assign(), append(), at()
21、empty(), size(), find(), swap() c_str();,Streaming File,The streaming file class library #include ifstream InFile(“in.txt”); - Input file ofstream OutFile(“out.txt”); - Output file ofstream OutFile(“out.txt”, ios_base:app); - Output file (append mode) fstream IOFile(“io.txt”); - In-&Out-put file Usa
22、ge InFile , OutFile , File.close(), On Failure, object will be evaluated as false if (! OutFile) cout “Open Failed!”,Summary,Important concepts in C, still useful in C+ C+ coding style Namespace Vector class template string & streaming file class library,Excises,Coding: Create a program that counts
23、the occurrence of the word that in a file (use the string class operator = to find the word) Create a vector and put 25 numbers into it. Then square each number and put the result back into the same location in the vector. Display the vector before and after the multiplications. Create two functions
24、, one that takes a string* and one that takes a string&. Each of these functions should modify the outside string object in its own unique way. In main(), create and initialize a string object, print it, then pass it to each of the two functions, printing the results. Create a struct that holds two
25、string objects and one int. Use a typedef for the struct name. Create an instance of the struct, initialize all three values in your instance, and print them out. Take the address of your instance and assign it to a pointer to your struct type. Change the three values in your instance and print them
26、 out, all using the pointer.,Programming Philosophy The Tao Of Programming,Part 1 - The Silent Void,Thus spake the master programmer: 编程大师如是说: “When you have learned to snatch the error code from the trap frame, it will be time for you to leave.“ “当你从我手中夺走水晶球时,就是你离开的时候了。”,Programming Philosophy The
27、Tao Of Programming,Something mysterious is formed, born in the silent void. Waiting alone and unmoving, it is at once still and yet in constant motion. It is the source of all programs. I do not know its name, so I will call it the Tao of Programming. 寂静的虚空里诞生了神秘的东西,这种东西恒久存在永不消失,它是所有程序的根源所在,我不知道怎么形容
28、它,姑且称它为编程之道。 If the Tao is great, then the operating system is great. If the operating system is great, then the compiler is great. If the compiler is greater, then the applications is great. The user is pleased and there is harmony in the world. 如果道是完美的,那么操作系统就是完美的,如果操作系统是完美的,那么编译嚣就是完美的,如果编译嚣是完美的,那
29、么应用程序就是完美的,所以用户心满意足,整个世界因此和谐。 The Tao of Programming flows far away and returns on the wind of morning. 编程之道去如黄鹤来如晨风。,Programming Philosophy The Tao Of Programming,The Tao gave birth to machine language. Machine language gave birth to the assembler. 道生机器语言,机器语言生汇编嚣。 The assembler gave birth to the c
30、ompiler. Now there are ten thousand languages. 汇编器生编译器,最后产生上万种高级语言。 Each language has its purpose, however humble. Each language expresses the Yin and Yang of software. Each language has its place within the Tao. 不论多么的微不足道,每种语言都有它自己的目的,每种语言都表达了软件的阴阳两极。每种语言都各得其道。 But do not program in COBOL if you ca
31、n avoid it. 但是尽量不要用COBOL语言。,Programming Philosophy The Tao Of Programming,In the beginning was the Tao. The Tao gave birth to Space and Time. Therefore, Space and Time are the Yin and Yang of programming. 道之初,带来了空间和时间,所以,空间和时间是编程的阴阳两极。 Programmers that do not comprehend the Tao are always running ou
32、t of time and space for their programs. Programmers that comprehend the Tao always have enough time and space to accomplish their goals. 不懂编程之道的程序员常常把空间和时间消耗殆尽,得道的程序员则总是有足够的空间和时间去完成编程任务。 How could it be otherwise? 还会是什么样呢?,Programming Philosophy The Tao Of Programming,The wise programmer is told abo
33、ut the Tao and follows it. The average programmer is told about the Tao and searches for it. The foolish programmer is told about the Tao and laughs at it. 上士闻道,从而行之。中士闻道,谨而寻之。下士闻道,大笑之。 If it were not for laughter, there would be no Tao. 大笑不足为道。 The highest sounds are the hardest to hear. Going forw
34、ard is a way to retreat. Greater talent shows itself late in life. Even a perfect program still has bugs. 希音不闻,进即是退,大器晚成。任何程序都有漏洞。,Programming Philosophy The Tao Of Programming,Part 2 - The Ancient Masters,Thus spake the master programmer: 编程大师如是说: “After three days without programming, life becomes
35、 meaningless.“ 三日不编程,食肉无味。,Programming Philosophy The Tao Of Programming,The programmers of old were mysterious and profound. We cannot fathom their thoughts, so all we do is describe their appearance. 远古时代的编程大师们高深莫测,我们不能揣测他们的所思所想,只能描述外表所见。 Aware, like a fox crossing the water. Alert, like a general
36、 on the battlefield. Kind, like a hostess greeting her guests. Simple, like uncarved blocks of wood. Opaque, like black pools in darkened caves. 他达明,如狐狸过水;机警,如战场上的将军;和善,如主妇款待客人;简单,呆若木鸡;混沌,如深渊之水。 Who can tell the secrets of their hearts and minds? 谁能道尽他们的所有? The answer exists only in the Tao. 答案仅存于道。
37、,Programming Philosophy The Tao Of Programming,Grand Master Turing once dreamed that he was a machine. When he awoke he exclaimed: 超级大师图灵曾梦见自己是一台机器,醒后他这样回忆: “I dont know whether I am Turing dreaming that I am a machine, or a machine dreaming that I am Turing!“ “我不知道是图灵梦见自己变成机器还是机器梦见自己变成图灵。”,Programm
38、ing Philosophy The Tao Of Programming,A programmer from a very large computer company went to a software conference and then returned to report to his manager, saying: “What sort of programmers work for other companies? They behaved badly and were unconcerned with appearances. Their hair was long an
39、d unkempt and their clothes were wrinkled and old. They crashed out hospitality suites and they made rude noises during my presentation.“ 一个大公司的程序员参加一个软件会议后向他的主管汇报:“那些别的公司的程序员都是些什么样的人呀?他们举止不雅,不修边幅,头发蓬乱,衣服破旧,根本不热情好客,还在我说话的时候乱嚷嚷。”,Programming Philosophy The Tao Of Programming,The manager said: “I shou
40、ld have never sent you to the conference. Those programmers live beyond the physical world. They consider life absurd, an accidental coincidence. They come and go without knowing limitations. Without a care, they live only for their programs. Why should they bother with social conventions?“ 他的主管说:“我
41、不应该让你参加这次会议,这些程序员生活在现实世界之外。他们认为生活是可笑的,一场意外的偶然而已。他们来去自由,无所牵挂,他们只为他们的程序生活。为什么要用世俗的烦扰去扰乱他们呢?” “They are alive within the Tao.“ “他们生活在道中”。,Programming Philosophy The Tao Of Programming,A novice asked the Master: “Here is a programmer that never designs, documents, or tests his programs. Yet all who know
42、 him consider him one of the best programmers in the world. Why is this?“ 一个初学者问主管经理:“有一个程序员,他从来不预先设计,也不写文档,甚至不测试他的程序,但是知道他的人都认为他是世界上最伟大的程序员,为什么呢?”,Programming Philosophy The Tao Of Programming,The Master replies: “That programmer has mastered the Tao. He has gone beyond the need for design; he does
43、 not become angry when the system crashes, but accepts the universe without concern. He has gone beyond the need for documentation; he no longer cares if anyone else sees his code. He has gone beyond the need for testing; each of his programs are perfect within themselves, serene and elegant, their purpose self-evident. Truly, he has entered the mystery of the Tao.“ 经理说:“那个程序员掌握了道。他不需要预先进行设计;系统崩溃时他也从不烦燥,只是接受发生的一切而不管发生的事是好是坏 。他不需要写文档,他从不顾及有没有人看他写的代码。他也不需要进行测试;他写的每个程序都有一个完美的自我,平静而优雅,它们的目的不言自明。他已经真正掌握了道的精髓。”,