回顧:在第0章中我總結了重要的知識點有:字符串直接量、表達式的結構,操作數和操作符的定義,還有表達式的副作用、和std::cout結合<<操作符返回std::ostream類型,等知識點。
代碼如下
1 // ask for person's name, and greet the person
2
3 #include <iostream>
4 #include <string>
5
6 int main() {
7 //ask for the person's name
8 std::cout << "Please enter your first name: ";
9
10 //read the name
11 std::string name;
12 std::cin >> name;
13
14 //write a greeting
15 std::cout << "Hello, " << name << "!" << std::endl;
16 return 0;
17 }
#name就是一個變量(它的類型是std::string),而變量是一個有名字的對象(變量一定是對象,但對象不一定為變量,因為對象可以沒有名字,而且對象對應系統中的一塊內存)。
#line 11:是一個definition,即是一個定義,定義了一個名叫做name的std::string類型的變量。而且出現在一個函數提中,所以是一個local variable,當程序執行放到},就會銷毀name變量,并且釋放name占用的內存,以讓其他變量使用。
#line 12:>>從標準輸入中讀取一個字符串,并且保存它在name對象中。當通過標準庫讀取一個字符串時,他會忽略輸入中的所有空白符,而吧其他字符讀取到name中,直到它遇到其他空白符或者文件結束標志。因此std::cin >> name;的結果是從標準輸入中讀取一個單詞。
#輸入輸出庫會把它的輸出保存在buffer的內部數據結構上,通過緩存可以優化輸出操作。(因為許多操作系統在向輸出設備寫入字符時需要花大量的時間)
#有三個事件會促使系統刷新緩沖區。
#第一,緩存區滿了,自動刷新。
#第二,標準庫被要求讀取標準輸入流。(即std::cin是std::istream類型)。如line 12.
#第三,顯示的要求刷新緩沖。(std::endl結束了輸出行,并且刷新緩沖區)
#
1 //ask for a person's name, and generate a framed greeting
2 #include <iostream>
3 #include <string>
4
5 int main() {
6 std::cout << "Please enter your first name: ";
7 std::string name;
8 std::cin >> name;
9 //build the message that we intend to write
10 const std::string greeting = "Hello, " + name + "!";
11
12 //build the second and fourth lines of the input
13 const std::string spaces(greeting.size(), ' ');
14 const std::string second = "* " + spaces + " *";
15
16 //build the first and fifth lines of the output
17 const std::string first(second.size(), '*');
18
19 //write it all
20 std::cout << std::endl;
21 std::cout << first <<std::endl;
22 std::cout << second << std::endl;
23 std::cout << "* " << greeting << " *" << std::endl;
24 std::cout << second << std::endl;
25 std::cout << first << std::endl;
26
27 return 0;
28 }
#greeting的定義包含三個新的概念
#第一個:在定義變量時候,可以給定它的值。
#第二個:用+來連接字符串,但是這兩個中必須至少有一個是string對象。(+也是左結合性的)
#(+在這里是連接作用),引出overloaded(重載)概念,這個操作符被重載了,因為其對不同操作數有不同的含義。
#第三個:const可以作為變量定義的一部分,這么做保證在變量生存期內,不改變它的值。
#如果一個變量定義為const,必須在定義時初始化,否則后面就不能再初始化。
#const std::string spaces(greeting.size(), ' ');來介紹另三個概念
#第一個:構造函數
#第二個:成員函數(member function),其實可以吧greeting看成對象,向其發送size消息獲取其長度。
#第三個:字符直接量。(用'(單引號),而字符串直接量則是用“號).字符直接量的類型是內置于語言核心的char類型。