1
0
mirror of https://github.com/adambard/learnxinyminutes-docs.git synced 2025-08-06 14:56:54 +02:00

[c++/cn] Complete the whole translation.

This commit is contained in:
Arnie97
2015-04-11 12:31:11 +08:00
parent cfb4d5922d
commit cb69cff1be

View File

@@ -9,66 +9,66 @@ translators:
lang: zh-cn lang: zh-cn
--- ---
C++是一種系統編程語言。用它的明者, C++是一种系统编程语言。用它的明者,
[Bjarne Stroustrup的](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)來說C++的設計目標是: [Bjarne Stroustrup的](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)来说C++的设计目标是:
-爲「更好的C語言」 -为“更好的C语言”
- 支持數據的抽象與封裝 - 支持数据的抽象与封装
- 支持面向對象編 - 支持面向对象编
- 支持泛型 - 支持泛型
C++提供了硬件的密控制正如C言一 C++提供了硬件的密控制正如C言一
夠編譯爲機器語言,由理器直接行。 够编译为机器语言,由理器直接行。
此同,它也提供了泛型、常和等高功能。 此同,它也提供了泛型、常和等高功能。
然C++的法可能比某些出現較晚的言更複雜,它仍然得到了人的青睞—— 然C++的法可能比某些出现较晚的言更复杂,它仍然得到了人的青睞——
功能速度的平衡使C++成了目前用最泛的系統編程語言之一。 功能速度的平衡使C++成了目前用最广泛的系统编程语言之一。
```c++ ```c++
//////////////// ////////////////
// 與C語言的比 // 与C语言的比
//////////////// ////////////////
// C++_乎_是C言的一超集,它與C語言的基本法有多相同之 // C++_乎_是C言的一超集,它与C语言的基本法有多相同之
// 例如量和函數的聲明,原生數據類型等等。 // 例如量和函数的声明,原生数据类型等等。
// 和C言一在C++中,你的程序會從main()開始執行, // 和C言一在C++中,你的程序会从main()开始执行,
// 該函數的返回值應當爲int型這個返回值會作爲程序的退出狀態值。 // 该函数的返回值应当为int型这个返回值会作为程序的退出状态值。
// 不,大多數的編譯gccclang等也接受 void main() 的函原型。 // 不,大多数的编译gccclang等也接受 void main() 的函原型。
// 參見 http://en.wikipedia.org/wiki/Exit_status 來獲取更多信息) // 参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息)
int main(int argc, char** argv) int main(int argc, char** argv)
{ {
// 和C言一,命令行參數通過argc和argv傳遞 // 和C言一,命令行参数通过argc和argv传递
// argc代表命令行參數的數量, // argc代表命令行参数的数量,
// 而argv是一包含「C語言風格字符串char *)的數組 // 而argv是一包含“C语言风格字符串char *)的数组
// 其中每字符串代表一命令行參數的內容, // 其中每字符串代表一命令行参数的内容,
// 首命令行參數是調用該程序所使用的名 // 首命令行参数是调用该程序所使用的名
// 如果你不心命令行參數的值argc和argv可以被忽略。 // 如果你不心命令行参数的值argc和argv可以被忽略。
// 此你可以用int main()作爲函數原型。 // 此你可以用int main()作为函数原型。
// 退出狀態值爲0時,表示程序行成功 // 退出状态值为0时,表示程序行成功
return 0; return 0;
} }
// 然而C++和C言也有一些區別 // 然而C++和C言也有一些区别
// 在C++中,字符字面量的大小是一個字節 // 在C++中,字符字面量的大小是一个字节
sizeof('c') == 1 sizeof('c') == 1
// 在C言中,字符字面量的大小int相同。 // 在C言中,字符字面量的大小int相同。
sizeof('c') == sizeof(10) sizeof('c') == sizeof(10)
// C++的函原型與函數定義是嚴格匹配的 // C++的函原型与函数定义是严格匹配的
void func(); // 這個函數不能接受任何參數 void func(); // 这个函数不能接受任何参数
// 而在C言中 // 而在C言中
void func(); // 這個函數能接受任意量的參數 void func(); // 这个函数能接受任意量的参数
// 在C++中用nullptr代替C言中的NULL // 在C++中用nullptr代替C言中的NULL
int* ip = nullptr; int* ip = nullptr;
// C++也可以使用C言的標準頭文件, // C++也可以使用C言的标准头文件,
// 但是需要加上前綴「c」並去掉末尾的.h // 但是需要加上前缀“c”并去掉末尾的.h
#include <cstdio> #include <cstdio>
int main() int main()
@@ -78,10 +78,10 @@ int main()
} }
/////////// ///////////
// 函數重載 // 函数重载
/////////// ///////////
// C++支持函數重載【provided each function takes different parameters.】 // C++支持函数重载,你可以定义一组名称相同而参数不同的函数。
void print(char const* myString) void print(char const* myString)
{ {
@@ -95,20 +95,20 @@ void print(int myInt)
int main() int main()
{ {
print("Hello"); // 解析 void print(const char*) print("Hello"); // 解析 void print(const char*)
print(15); // 解析 void print(int) print(15); // 解析 void print(int)
} }
/////////////////// ///////////////////
// 函數參數的默 // 函数参数的默
/////////////////// ///////////////////
// 你可以爲函數的參數指定默值, // 你可以为函数的参数指定默值,
// 它們將會在調用者有提供相應參數時被使用。 // 它们将会在调用者有提供相应参数时被使用。
void doSomethingWithInts(int a = 1, int b = 4) void doSomethingWithInts(int a = 1, int b = 4)
{ {
// 對兩個參數進行一些操作 // 对两个参数进行一些操作
} }
int main() int main()
@@ -118,19 +118,19 @@ int main()
doSomethingWithInts(20, 5); // a = 20, b = 5 doSomethingWithInts(20, 5); // a = 20, b = 5
} }
// 默認參數必須放在所有的常規參數之後 // 默认参数必须放在所有的常规参数之后
void invalidDeclaration(int a = 1, int b) // 這是錯誤的! void invalidDeclaration(int a = 1, int b) // 这是错误的!
{ {
} }
/////////// ///////////
// 命名空 // 命名空
/////////// ///////////
// 命名空間爲變量、函和其他明提供了【separate】的作用域。 // 命名空间为变量、函和其他明提供了分离的的作用域。
// 命名空可以嵌套使用。 // 命名空可以嵌套使用。
namespace First { namespace First {
namespace Nested { namespace Nested {
@@ -138,8 +138,8 @@ namespace First {
{ {
printf("This is First::Nested::foo\n"); printf("This is First::Nested::foo\n");
} }
} // 束嵌套的命名空Nested } // 束嵌套的命名空Nested
} // 束命名空First } // 束命名空First
namespace Second { namespace Second {
void foo() void foo()
@@ -155,38 +155,38 @@ void foo()
int main() int main()
{ {
// 如果有特指定,就從「Second中取得所需的容。 // 如果有特指定,就从“Second中取得所需的容。
using namespace Second; using namespace Second;
foo(); // 顯示「This is Second::foo foo(); // 显示“This is Second::foo
First::Nested::foo(); // 顯示「This is First::Nested::foo First::Nested::foo(); // 显示“This is First::Nested::foo
::foo(); // 顯示「This is global foo ::foo(); // 显示“This is global foo
} }
//////////// ////////////
// 入/ // 入/
//////////// ////////////
// C++使用「流」來輸入輸出。<<是流的插入算符,>>是流提取算符。 // C++使用“流”来输入输出。<<是流的插入算符,>>是流提取算符。
// cin、cout、和cerr分代表 // cin、cout、和cerr分代表
// stdin標準輸、stdout標準輸和stderr標準錯誤)。 // stdin标准输、stdout标准输和stderr标准错误)。
#include <iostream> // 引入包含入/出流的文件 #include <iostream> // 引入包含入/出流的文件
using namespace std; // 輸入輸出流在std命名空(也就是標準庫)中。 using namespace std; // 输入输出流在std命名空(也就是标准库)中。
int main() int main()
{ {
int myInt; int myInt;
// 在標準輸出(端/示器)中 // 在标准输出(端/示器)中
cout << "Enter your favorite number:\n"; cout << "Enter your favorite number:\n";
// 從標準輸入(鍵盤)獲得一 // 从标准输入(键盘)获得一
cin >> myInt; cin >> myInt;
// cout也提供了格式化功能 // cout也提供了格式化功能
cout << "Your favorite number is " << myInt << "\n"; cout << "Your favorite number is " << myInt << "\n";
// 顯示「Your favorite number is <myInt> // 显示“Your favorite number is <myInt>
cerr << "Used for error messages"; cerr << "Used for error messages";
} }
@@ -195,20 +195,20 @@ int main()
// 字符串 // 字符串
///////// /////////
// C++中的字符串是象,它有很多成員函數 // C++中的字符串是象,它有很多成员函数
#include <string> #include <string>
using namespace std; // 字符串也在std命名空間(標準庫)中。 using namespace std; // 字符串也在std命名空间(标准库)中。
string myString = "Hello"; string myString = "Hello";
string myOtherString = " World"; string myOtherString = " World";
// + 可以用於連接字符串。 // + 可以用于连接字符串。
cout << myString + myOtherString; // "Hello World" cout << myString + myOtherString; // "Hello World"
cout << myString + " You"; // "Hello You" cout << myString + " You"; // "Hello You"
// C++中的字符串是可的,具有「值語義」 // C++中的字符串是可的,具有“值语义”
myString.append(" Dog"); myString.append(" Dog");
cout << myString; // "Hello Dog" cout << myString; // "Hello Dog"
@@ -217,11 +217,11 @@ cout << myString; // "Hello Dog"
// 引用 // 引用
///////////// /////////////
// 除了支持C言中的指針類型以外C++提供了_引用_。 // 除了支持C言中的指针类型以外C++提供了_引用_。
// 引用是一特殊的指針類型,一旦被定就不能重新值,且不能被設置爲空值。 // 引用是一特殊的指针类型,一旦被定就不能重新值,且不能被设置为空值。
// 使用引用時的語法與原變量相同: // 使用引用时的语法与原变量相同:
// 也就是說,對引用類型進行解引用,不需要使用* // 也就是说,对引用类型进行解引用,不需要使用*
// 賦值時也不需要用&取地址。 // 赋值时也不需要用&取地址。
using namespace std; using namespace std;
@@ -229,76 +229,76 @@ string foo = "I am foo";
string bar = "I am bar"; string bar = "I am bar";
string& fooRef = foo; // 建立了一個對foo的引用。 string& fooRef = foo; // 建立了一个对foo的引用。
fooRef += ". Hi!"; // 通引用修改foo的值 fooRef += ". Hi!"; // 通引用修改foo的值
cout << fooRef; // "I am foo. Hi!" cout << fooRef; // "I am foo. Hi!"
// 這句話的並不會改變fooRef的指向其效果與「foo = bar相同。 // 这句话的并不会改变fooRef的指向其效果与“foo = bar相同。
// 也就是,在執行這條語句之foo == "I am bar"。 // 也就是,在执行这条语句之foo == "I am bar"。
fooRef = bar; fooRef = bar;
const string& barRef = bar; // 建立指向bar的常量引用。 const string& barRef = bar; // 建立指向bar的常量引用。
// 和C言中一,(指和引用)聲明爲常量時,對應的值不能被修改。 // 和C言中一,(指和引用)声明为常量时,对应的值不能被修改。
barRef += ". Hi!"; // 這是錯誤的,不能修改一常量引用的值。 barRef += ". Hi!"; // 这是错误的,不能修改一常量引用的值。
/////////////////// ///////////////////
// 類與面向對象編 // 类与面向对象编
/////////////////// ///////////////////
// 有關類的第一示例 // 有关类的第一示例
#include <iostream> #include <iostream>
// 明一個類 // 明一个类
// 通常在文件(.h或.hpp明。 // 通常在文件(.h或.hpp明。
class Dog { class Dog {
// 成員變量和成員函數默認情況下是私有private的。 // 成员变量和成员函数默认情况下是私有private的。
std::string name; std::string name;
int weight; int weight;
// 在這個標籤之後,所有明都是公有public // 在这个标签之后,所有明都是公有public
// 直到重新指定private:(私有承)或protected:(保護繼承) // 直到重新指定private:(私有承)或protected:(保护继承)
public: public:
// 默認的構造器 // 默认的构造器
Dog(); Dog();
// 這裏是成員函數聲明的一例子。 // 这里是成员函数声明的一例子。
// 可以注意到,我在此使用了std::string而不是using namespace std // 可以注意到,我在此使用了std::string而不是using namespace std
// 句using namespace絕不應當出現在頭文件中。 // 句using namespace绝不应当出现在头文件中。
void setName(const std::string& dogsName); void setName(const std::string& dogsName);
void setWeight(int dogsWeight); void setWeight(int dogsWeight);
// 如果一個函數不對對象的狀態進行修改, // 如果一个函数不对对象的状态进行修改,
// 應當在聲明中加上const。 // 应当在声明中加上const。
// 這樣,你就可以對一個以常量方式引用的對象執行該操作。 // 这样,你就可以对一个以常量方式引用的对象执行该操作。
// 同可以注意到,當父類的成員函數需要被子類重寫時 // 同可以注意到,当父类的成员函数需要被子类重写时
// 父中的函數必須被顯式聲明爲_虛函數virtual_。 // 父中的函数必须被显式声明为_虚函数virtual_。
// 考到性能方面的因素,函數默認情況下不會被聲明爲虛函數 // 考到性能方面的因素,函数默认情况下不会被声明为虚函数
virtual void print() const; virtual void print() const;
// 函也可以在class body部定 // 函也可以在class body部定
// 這樣定義的函數會自動成爲內聯函數 // 这样定义的函数会自动成为内联函数
void bark() const { std::cout << name << " barks!\n" } void bark() const { std::cout << name << " barks!\n" }
// 除了造器以外C++提供了析器。 // 除了造器以外C++提供了析器。
// 當一個對象被除或者脫離其定義域時時,它的析構函數會被調用。 // 当一个对象被除或者脱离其定义域时时,它的析构函数会被调用。
// 使得RAII這樣的強大範式(參見下文)成可能。 // 使得RAII这样的强大范式(参见下文)成可能。
// 了衍生出子類來,基的析構函數必須定義爲虛函數 // 了衍生出子类来,基的析构函数必须定义为虚函数
virtual ~Dog(); virtual ~Dog();
}; // 在的定義之後,要加一個分號 }; // 在的定义之后,要加一个分号
}; // 住,在的定義之後,要加一個分號 }; // 住,在的定义之后,要加一个分号
// 的成員函數通常在.cpp文件中實現 // 的成员函数通常在.cpp文件中实现
void Dog::Dog() void Dog::Dog()
{ {
std::cout << "A dog has been constructed\n"; std::cout << "A dog has been constructed\n";
} }
// 象(例如字符串)應當以引用的形式傳遞 // 象(例如字符串)应当以引用的形式传递
// 對於不需要修改的象,最好使用常量引用。 // 对于不需要修改的象,最好使用常量引用。
void Dog::setName(const std::string& dogsName) void Dog::setName(const std::string& dogsName)
{ {
name = dogsName; name = dogsName;
@@ -309,7 +309,7 @@ void Dog::setWeight(int dogsWeight)
weight = dogsWeight; weight = dogsWeight;
} }
// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時出現 // 虚函数的virtual关键字只需要在声明时使用,不需要在定义时出现
void Dog::print() const void Dog::print() const
{ {
std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
@@ -325,7 +325,7 @@ void Dog::setWeight(int dogsWeight)
weight = dogsWeight; weight = dogsWeight;
} }
// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時重複 // 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复
void Dog::print() const void Dog::print() const
{ {
std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
@@ -337,32 +337,32 @@ void Dog::~Dog()
} }
int main() { int main() {
Dog myDog; // 此時顯示「A dog has been constructed Dog myDog; // 此时显示“A dog has been constructed
myDog.setName("Barkley"); myDog.setName("Barkley");
myDog.setWeight(10); myDog.setWeight(10);
myDog.printDog(); // 顯示「Dog is Barkley and weighs 10 kg myDog.printDog(); // 显示“Dog is Barkley and weighs 10 kg
return 0; return 0;
} // 顯示「Goodbye Barkley } // 显示“Goodbye Barkley
// 承: // 承:
// 這個類繼承了Dog中的公有public和保protected // 这个类继承了Dog中的公有public和保protected
class OwnedDog : public Dog { class OwnedDog : public Dog {
void setOwner(const std::string& dogsOwner) void setOwner(const std::string& dogsOwner)
// 重OwnedDogs的print方法。 // 重OwnedDogs的print方法。
// 如果你不熟悉子類多態的話,可以參考這個頁面中的概述: // 如果你不熟悉子类多态的话,可以参考这个页面中的概述:
// http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
// override關鍵字是可的,它保你是在重寫基類中的方法。 // override关键字是可的,它保你所重写的是基类中的方法。
void print() const override; void print() const override;
private: private:
std::string owner; std::string owner;
}; };
// 此同,在對應的.cpp文件 // 此同,在对应的.cpp文件
void OwnedDog::setOwner(const std::string& dogsOwner) void OwnedDog::setOwner(const std::string& dogsOwner)
{ {
@@ -371,7 +371,7 @@ void OwnedDog::setOwner(const std::string& dogsOwner)
void OwnedDog::print() const void OwnedDog::print() const
{ {
Dog::print(); // 調用基Dog中的print方法 Dog::print(); // 用基Dog中的print方法
// "Dog is <name> and weights <weight>" // "Dog is <name> and weights <weight>"
std::cout << "Dog is owned by " << owner << "\n"; std::cout << "Dog is owned by " << owner << "\n";
@@ -379,45 +379,46 @@ void OwnedDog::print() const
} }
///////////////////// /////////////////////
// 初始化與運算符重 // 初始化与运算符重
///////////////////// /////////////////////
// 在C++中,你可以重載+、-、*、/等運算符的行爲。 // 在C++中,通过定义一些特殊名称的函数,
// 【This is done by defining a function // 你可以重载+、-、*、/等运算符的行为。
// which is called whenever the operator is used. // 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。
#include <iostream> #include <iostream>
using namespace std; using namespace std;
class Point { class Point {
public: public:
// 可以以這樣的方式爲成員變量設置默值。 // 可以以这样的方式为成员变量设置默值。
double x = 0; double x = 0;
double y = 0; double y = 0;
// 【Define a default constructor which does nothing // 定义一个默认的构造器。
// but initialize the Point to the default value (0, 0) // 除了将Point初始化为(0, 0)以外,这个函数什么都不做。
Point() { }; Point() { };
// 【The following syntax is known as an initialization list // 下面使用的语法称为初始化列表,
// and is the proper way to initialize class member values // 这是初始化类中成员变量的正确方式。
Point (double a, double b) : Point (double a, double b) :
x(a), x(a),
y(b) y(b)
{ /* 【Do nothing except initialize the values */ } { /* 除了初始化成员变量外,什么都不做 */ }
// 重 + 算符 // 重 + 算符
Point operator+(const Point& rhs) const; Point operator+(const Point& rhs) const;
// 重 += 算符 // 重 += 算符
Point& operator+=(const Point& rhs); Point& operator+=(const Point& rhs);
// 增加 - 和 -= 算符也是有意的,這裏不再述。 // 增加 - 和 -= 算符也是有意的,但这里不再述。
}; };
Point Point::operator+(const Point& rhs) const Point Point::operator+(const Point& rhs) const
{ {
// 【Create a new point that is the sum of this one and rhs. // 创建一个新的点,
// 其横纵坐标分别为这个点与另一点在对应方向上的坐标之和。
return Point(x + rhs.x, y + rhs.y); return Point(x + rhs.x, y + rhs.y);
} }
@@ -431,88 +432,88 @@ Point& Point::operator+=(const Point& rhs)
int main () { int main () {
Point up (0,1); Point up (0,1);
Point right (1,0); Point right (1,0);
// 這裏調用了Point型的算符「+」 // 这里使用了Point型的算符“+”
// 調用upPoint型)的「+」方法,以right作爲函數的參數 // 用upPoint型)的“+”方法,以right作为函数的参数
Point result = up + right; Point result = up + right;
// 顯示「Result is upright (1,1) // 显示“Result is upright (1,1)
cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
return 0; return 0;
} }
/////////// ///////////
// 異常處 // 异常处
/////////// ///////////
// 標準庫中提供了一些基本的異常類 // 标准库中提供了一些基本的异常类
// 參見http://en.cppreference.com/w/cpp/error/exception // 参见http://en.cppreference.com/w/cpp/error/exception
// 但是,其他任何型也可以作爲一個異常被拋出 // 但是,其他任何型也可以作为一个异常被拋出
#include <exception> #include <exception>
// 在_try_代碼塊中拋出的常可以被隨後的_catch_捕 // 在_try_代码块中拋出的常可以被随后的_catch_捕
try { try {
// 不要用 _new_關鍵字在堆上爲異常分配空 // 不要用 _new_关键字在堆上为异常分配空
throw std::exception("A problem occurred"); throw std::exception("A problem occurred");
} }
// 如果拋出的常是一個對象,可以用常量引用來捕獲 // 如果拋出的常是一个对象,可以用常量引用来捕获
catch (const std::exception& ex) catch (const std::exception& ex)
{ {
std::cout << ex.what(); std::cout << ex.what();
// 捕尚未被_catch_理的所有錯誤 // 捕尚未被_catch_理的所有错误
} catch (...) } catch (...)
{ {
std::cout << "Unknown exception caught"; std::cout << "Unknown exception caught";
throw; // 重新拋出 throw; // 重新拋出
} }
/////// ///////
// RAII // RAII
/////// ///////
// RAII指的是资源获取就是初始化Resource Allocation Is Initialization // RAII指的是资源获取就是初始化Resource Allocation Is Initialization
// 它被作C++中最大的編程範式之一。 // 它被作C++中最大的编程范式之一。
// 簡單說來,它指的是,用造函數來獲取一個對象的源, // 简单说来,它指的是,用造函数来获取一个对象的源,
// 相的,借助析構函數來釋放對象的源。 // 相的,借助析构函数来释放对象的源。
// 了理解這一範式的用處,讓我們考慮某個函數使用文件句柄的情 // 了理解这一范式的用处,让我们考虑某个函数使用文件句柄的情
void doSomethingWithAFile(const char* filename) void doSomethingWithAFile(const char* filename)
{ {
// 首先,讓我們假設一切都會順利進行。 // 首先,让我们假设一切都会顺利进行。
FILE* fh = fopen(filename, "r"); // 以只模式打文件 FILE* fh = fopen(filename, "r"); // 以只模式打文件
doSomethingWithTheFile(fh); doSomethingWithTheFile(fh);
doSomethingElseWithIt(fh); doSomethingElseWithIt(fh);
fclose(fh); // 關閉文件句柄 fclose(fh); // 关闭文件句柄
} }
// 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜 // 不幸的是,随着错误处理机制的引入,事情会变得复杂
// 假fopen函有可能行失 // 假fopen函有可能行失
// 而doSomethingWithTheFile和doSomethingElseWithIt在失敗時返回錯誤代碼 // 而doSomethingWithTheFile和doSomethingElseWithIt在失败时返回错误代码
// 雖然異常是C++中處理錯誤的推方式, // 虽然异常是C++中处理错误的推方式,
// 但是某些程序尤其是有C言背景的,並不認可異常捕獲機制的作用)。 // 但是某些程序尤其是有C言背景的,并不认可异常捕获机制的作用)。
// 在,我們必須檢查每個函數調用是否成功行,並在問題發生的時候關閉文件句柄。 // 在,我们必须检查每个函数调用是否成功行,并在问题发生的时候关闭文件句柄。
bool doSomethingWithAFile(const char* filename) bool doSomethingWithAFile(const char* filename)
{ {
FILE* fh = fopen(filename, "r"); // 以只模式打文件 FILE* fh = fopen(filename, "r"); // 以只模式打文件
if (fh == nullptr) // 當執行失是,返回的指是nullptr if (fh == nullptr) // 当执行失是,返回的指是nullptr
return false; // 向調用者彙報錯誤 return false; // 向用者汇报错误
// 假設每個函數會在執行失敗時返回false // 假设每个函数会在执行失败时返回false
if (!doSomethingWithTheFile(fh)) { if (!doSomethingWithTheFile(fh)) {
fclose(fh); // Close the file handle so it doesn't leak. fclose(fh); // 关闭文件句柄,避免造成内存泄漏。
return false; // 反饋錯誤 return false; // 反馈错误
} }
if (!doSomethingElseWithIt(fh)) { if (!doSomethingElseWithIt(fh)) {
fclose(fh); // Close the file handle so it doesn't leak. fclose(fh); // 关闭文件句柄
return false; // 反饋錯誤 return false; // 反馈错误
} }
fclose(fh); // Close the file handle so it doesn't leak. fclose(fh); // 关闭文件句柄
return true; // 指示函已成功 return true; // 指示函已成功
} }
// C言的程序通常借助goto語句簡化上面的代 // C言的程序通常借助goto语句简化上面的代
bool doSomethingWithAFile(const char* filename) bool doSomethingWithAFile(const char* filename)
{ {
FILE* fh = fopen(filename, "r"); FILE* fh = fopen(filename, "r");
@@ -525,19 +526,19 @@ bool doSomethingWithAFile(const char* filename)
if (!doSomethingElseWithIt(fh)) if (!doSomethingElseWithIt(fh))
goto failure; goto failure;
fclose(fh); // 關閉文件 fclose(fh); // 关闭文件
return true; // 行成功 return true; // 行成功
failure: failure:
fclose(fh); fclose(fh);
return false; // 反饋錯誤 return false; // 反馈错误
} }
// 如果用常捕獲機制來指示錯誤的話 // 如果用常捕获机制来指示错误的话
// 代碼會變得清晰一些,但是仍然有化的餘地。 // 代码会变得清晰一些,但是仍然有化的餘地。
void doSomethingWithAFile(const char* filename) void doSomethingWithAFile(const char* filename)
{ {
FILE* fh = fopen(filename, "r"); // 以只模式打文件 FILE* fh = fopen(filename, "r"); // 以只模式打文件
if (fh == nullptr) if (fh == nullptr)
throw std::exception("Could not open the file."); throw std::exception("Could not open the file.");
@@ -546,45 +547,44 @@ void doSomethingWithAFile(const char* filename)
doSomethingElseWithIt(fh); doSomethingElseWithIt(fh);
} }
catch (...) { catch (...) {
fclose(fh); // 保證出錯的時候文件被正確關閉 fclose(fh); // 保证出错的时候文件被正确关闭
throw; // Then re-throw the exception. throw; // Then re-throw the exception.
} }
fclose(fh); // 關閉文件 fclose(fh); // 关闭文件
// 所有工作利完成 // 所有工作利完成
} }
// 【Compare this to the use of C++'s file stream class (fstream) // 相比之下使用C++中的文件流类(fstream)时,
// fstream利用自己的析構器來關閉文件句柄。 // fstream利用自己的析构器来关闭文件句柄。
// 【Recall from above that destructors are automatically called // 只要离开了某一对象的定义域,它的析构函数就会被自动调用。
// whenver an object falls out of scope.
void doSomethingWithAFile(const std::string& filename) void doSomethingWithAFile(const std::string& filename)
{ {
// ifstream是入文件流input file stream簡稱 // ifstream是入文件流input file stream简称
std::ifstream fh(filename); // Open the file std::ifstream fh(filename); // 打开一个文件
// 文件行一些操作 // 文件行一些操作
doSomethingWithTheFile(fh); doSomethingWithTheFile(fh);
doSomethingElseWithIt(fh); doSomethingElseWithIt(fh);
} // 文件已被析器自動關閉 } // 文件已被析器自动关闭
// 上面幾種方式相比,這種方式有着_明_的優勢 // 上面几种方式相比,这种方式有着_明_的优势
// 1. 無論發生了什麼情況,資源(此例中是文件句柄)都被正確關閉 // 1. 无论发生了什么情况,资源(此例中是文件句柄)都被正确关闭
// 只要你正使用了析就_不_因爲忘記關閉句柄,造成源的泄漏。 // 只要你正使用了析就_不_因为忘记关闭句柄,造成源的泄漏。
// 2. 可以注意到,通過這種方式寫出來的代十分簡潔 // 2. 可以注意到,通过这种方式写出来的代十分简洁
// 析構器會在後臺關閉文件句柄,不再需要你操心這些瑣事。 // 析构器会在后臺关闭文件句柄,不再需要你操心这些琐事。
// 3. 【The code is exception safe. // 3. 这种方式的代码具有异常安全性。
// 無論在函中的何拋出常,都不會阻礙對文件源的放。 // 无论在函中的何拋出常,都不会阻碍对文件源的放。
// 地道的C++代碼應當把RAII的使用展到各種類型的源上,包括: // 地道的C++代码应当把RAII的使用展到各种类型的源上,包括:
// - 用unique_ptr和shared_ptr管理的 // - 用unique_ptr和shared_ptr管理的
// - 各種數據容器,例如標準庫中的表、向量(容量自動擴展的數組)、散列表等; // - 各种数据容器,例如标准库中的表、向量(容量自动扩展的数组)、散列表等;
// 當它們脫離作用域,析構器會自動釋放其中存的容。 // 当它们脱离作用域,析构器会自动释放其中存的容。
// - 用lock_guard和unique_lock實現的互斥 // - 用lock_guard和unique_lock实现的互斥
``` ```
擴展閱讀 扩展阅读
<http://cppreference.com/w/cpp> 提供了最新的語法參考。 <http://cppreference.com/w/cpp> 提供了最新的语法参考。
可以在 <http://cplusplus.com> 找到一些補充資料。 可以在 <http://cplusplus.com> 找到一些补充资料。