C++ Primer 第1章 Getting Started 筆記

2020-08-11 21:42:40

Section 1.1 Writing a Simple C++ Program

  • 每個 C++ 程式都包含一個或多個函數,其中必須有一個 main 函數
  • 操作系統通過呼叫 main 來執行一個 C++ 程式
int main()
{
	return 0;
}
  • 一個函數定義包含四部分:
  1. 返回值
  2. 函數名
  3. 參數列表(可能爲空)
  4. 函數體
  • main 函數要求返回值型別爲 int ,這是一個內建型別(built-in type)

  • 型別(Types):定義了數據元素的內容以及可以在數據上進行的操作

  • echo $? 可以得到程式執行的返回值

Section 1.2 A First Look at Input/Output

  • C++ 本身沒有定義任何語句來進行 I/O,但是它包含了很多標準庫來進行 I/O
  • 用的最多的是 iostream
  • 這個庫裏面有兩個很重要的型別 istream, ostream,分別表示輸入流和輸出流
  • 一個流表示向 IO 裝置讀或寫的一系列字元
  • 之所以用流來表示,其中暗含了字元是隨着時間依次序生成(或消耗)的
  • 標準庫定義了四個 IO 物件
  1. cinistream 型別的一個物件,表示標準輸入
  2. coutostream 型別的一個物件,表示標準輸出
  3. cerrostream 型別的一個物件,表示標準錯誤
  4. clogostream 型別的一個物件,主要生成執行的資訊
  • 舉一個例子:
#include<iostream>
int main(){
	std::cout << "Enter two numbers:" << std::endl;
	int v1 = 0, v2 = 0;
	std::cin >> v1 >> v2;
	std::cout << "The sum of " << v1 << " and " << v2
			  << " is " << v1 + v2 << std::endl;
	return 0;
}
  • 第一行 #include<iostream> 表示我們需要用到 iostream 庫,這是一個頭檔案
  • main 裏面的第一個語句執行了一個 expression (有一個或多個 operator 構成的一個計算單元)
  • << 運算子接受兩個 operands,左邊必須是 ostream 的一個物件,右邊是一個需要輸出的值,這個運算子將給定的值寫到給定的 ostream 物件中去,得到的結果是其左邊的 operand,所以得到的結果仍然是一個 ostream 的物件,因此等價於:
(std::cout << "Enter two numbers:") << std::endl;

以及

std::cout << "Enter two numbers:";
std::cout << std::endl;
  • 輸出的第一個值是一個字串常數(string literal),通過雙引號將一堆字元圍起來
  • 輸出的第二個是 endl ,這個東西叫做運運算元/操作符(manipulator),其作用是結束當前行,並重新整理裝置關聯的緩衝區,重新整理緩衝區(flushing the buffer)是爲了保證程式輸出的所有內容都已經寫到了輸出流中,而不是駐留在記憶體當中準備寫入。

在这里插入图片描述

  • 字首 std:: 表示 cout,endlstd 的名稱空間中進行定義
  • 名稱空間主要是爲了避免命名衝突
  • int v1 = 0, v2 = 0 是在初始化兩個變數

Section 1.3 A Word about Comments

  • 兩種註釋:/* *///

Section 1.4 Flow of Control

  • while
  • for
  • while(std::in >> value) 讀入直到 end-of-file (ctrl+d,win 是 ctrl+c)
  • if

Section 1.5 Introducing Classes

  • 一個類定義了一個型別以及在其上可以進行的操作
  • C++ 類的設計主要集中在使得定義出來的類操作起來類似於 built-in type
  • 讀寫 Sales_item
#include<iostream>
#include "Sales_item.h"
int main()
{
	Sales_item book;
	std::cin >> book;
	std::cout << book << std::endl;
	return 0;
}
  • 新增 Sales_item
#include<iostream>
#include "Sales_item.h"
int main()
{
	Sales_item item1, item2;
	std::cin >> item1 >> item2;
	std::cout << item1 + item2 << std::endl;
	return 0;
}
  • 成員函數
#include<iostream>
#include "Sales_item.h"
int main()
{
	Sales_item item1, item2;
	std::cin >> item1 >> item2;
	if(item1.isbn() == item2.isbn()) {
		std::cout << item1 + item2 << std::endl;
		return 0;
	} else {
		std::cerr << "should refer to same ISBN" << std::endl;
		return -1;
	}
}

Section 1.6 The Bookstore Program

#include <iostream>
#include "Sales_item.h"
int main()
{
	Sales_item total;
	if(std::cin >> total) {
		Sales_item trans;
		while(std::cin >> trans) {
			if(total.isbn() == trans.isbn())
				total += trans;
			else {
				std::cout << total << std::endl;
				total = trans;
			}
		}
		std::cout << total << std::endl;
	} else {
		std::cerr << "no data?" << std::endl;
		return -1;
	}
}