From 7c3de408077a494d644ad926a198fc7e31f7ab82 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 14 Mar 2015 12:42:52 +0800 Subject: [c++/cn] translation started. --- zh-cn/c++-cn.html.markdown | 579 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 579 insertions(+) create mode 100644 zh-cn/c++-cn.html.markdown (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown new file mode 100644 index 00000000..f1bdf158 --- /dev/null +++ b/zh-cn/c++-cn.html.markdown @@ -0,0 +1,579 @@ +--- +language: c++ +filename: learncpp.cpp +contributors: + - ["Steven Basart", "http://github.com/xksteven"] + - ["Matt Kline", "https://github.com/mrkline"] +translators: + - ["Arnie97", "https://github.com/Arnie97"] +lang: zh-cn +--- + +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++中,你的程序會從main()開始執行, +// 該函數的返回值應當爲int型,這個返回值會作爲程序的退出狀態值。 +// 不過,大多數的編譯器(gcc,clang等)也接受 void main() 的函數原型。 +// (參見 http://en.wikipedia.org/wiki/Exit_status 來獲取更多信息) +int main(int argc, char** argv) +{ + // 和C語言一樣,命令行參數通過argc和argv傳遞。 + // argc代表命令行參數的數量, + // 而argv是一個包含“C語言風格字符串”(char *)的數組, + // 其中每個字符串代表一個命令行參數的內容, + // 首個命令行參數是調用該程序時所使用的名稱。 + // 如果你不關心命令行參數的值,argc和argv可以被忽略。 + // 此時,你可以用int main()作爲函數原型。 + + // 退出狀態值爲0時,表示程序執行成功 + return 0; +} + +// 然而,C++和C語言也有一些區別: + +// 在C++中,字符字面量的大小是一個字節。 +sizeof('c') == 1 + +// 在C語言中,字符字面量的大小與int相同。 +sizeof('c') == sizeof(10) + + +// C++的函數原型與函數定義是嚴格匹配的 +void func(); // 這個函數不能接受任何參數 + +// 而在C語言中 +void func(); // 這個函數能接受任意數量的參數 + +// 在C++中,用nullptr代替C語言中的NULL +int* ip = nullptr; + +// C++也可以使用C語言的標準頭文件, +// 但是需要加上前綴“c”並去掉末尾的“.h”。 +#include + +int main() +{ + printf("Hello, world!\n"); + return 0; +} + +/////////// +// 函數重載 +/////////// + +// C++支持函數重載,provided each function takes different parameters. + +void print(char const* myString) +{ + printf("String %s\n", myString); +} + +void print(int myInt) +{ + printf("My int is %d", myInt); +} + +int main() +{ + print("Hello"); // 解析爲 void print(const char*) + print(15); // 解析爲 void print(int) +} + +/////////////////// +// 函數參數的默認值 +/////////////////// + +// 你可以爲函數的參數指定默認值, +// 它們將會在調用者沒有提供相應參數時被使用。 + +void doSomethingWithInts(int a = 1, int b = 4) +{ + // 對兩個參數進行一些操作 +} + +int main() +{ + doSomethingWithInts(); // a = 1, b = 4 + doSomethingWithInts(20); // a = 20, b = 4 + doSomethingWithInts(20, 5); // a = 20, b = 5 +} + +// 默認參數必須放在所有的常規參數之後。 + +void invalidDeclaration(int a = 1, int b) // 這是錯誤的! +{ +} + + +/////////// +// 命名空間 +/////////// + +// 命名空間爲變量、函數和其他聲明提供了【separate】的作用域。 +// 命名空間可以嵌套使用。 + +namespace First { + namespace Nested { + void foo() + { + printf("This is First::Nested::foo\n"); + } + } // end namespace Nested +} // end namespace First + +namespace Second { + void foo() + { + printf("This is Second::foo\n") + } +} + +void foo() +{ + printf("This is global foo\n"); +} + +int main() +{ + // 如果沒有特別指定,所有【對象】都使用【取自】"Second"中的【聲明】。 + using namespace Second; + + foo(); // 顯示 "This is Second::foo" + First::Nested::foo(); // 顯示 "This is First::Nested::foo" + ::foo(); // 顯示 "This is global foo" +} + +//////////// +// 輸入/輸出 +//////////// + +// C++使用“流”來輸入輸出。 +// cin、cout、和cerr分別代表stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 +// <<是流的插入運算符,>>是流提取運算符。 + +#include // Include for I/O streams + +using namespace std; // 輸入輸出流在std命名空間(也就是標準庫)中。 + +int main() +{ + int myInt; + + // 在標準輸出(終端/顯示器)中顯示 + cout << "Enter your favorite number:\n"; + // 從標準輸入(鍵盤)獲得一個值 + cin >> myInt; + + // cout can also be formatted + cout << "Your favorite number is " << myInt << "\n"; + // 顯示 "Your favorite number is " + + cerr << "Used for error messages"; +} + +///////// +// 字符串 +///////// + +// C++中的字符串是對象,它們有很多成員函數 +#include + +using namespace std; // 字符串也在std命名空間(標準庫)中。 + +string myString = "Hello"; +string myOtherString = " World"; + +// + 可以用於連接字符串。 +cout << myString + myOtherString; // "Hello World" + +cout << myString + " You"; // "Hello You" + +// C++中的字符串是可變的,具有“值語義”。 +myString.append(" Dog"); +cout << myString; // "Hello Dog" + + +///////////// +// 引用 +///////////// + +// 除了支持C語言中的指針類型以外,C++還提供了_引用_。 +// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且引用不能被設置爲空值。 +// 使用引用時的語法與原變量相同: +// 也就是說,對引用類型進行解引用時,不需要使用*; +// 賦值時也不需要用&來取地址。 + +using namespace std; + +string foo = "I am foo"; +string bar = "I am bar"; + + +string& fooRef = foo; // 建立了一個對foo的引用。 +fooRef += ". Hi!"; // 通過引用來修改foo的值 +cout << fooRef; // "I am foo. Hi!" + +// 這句話的並不會改變fooRef的指向,其效果與“foo = bar”相同。 +// 也就是說,在執行這條語句之後,foo == "I am bar"。 +fooRef = bar; + +const string& barRef = bar; // 建立指向bar的【const ref】。 +// 和C語言中一樣,聲明爲常數的值(包括指針和引用)不能被修改。 +barRef += ". Hi!"; // 這是錯誤的,【const ref】不能被修改。 + +/////////////////// +// 類與面向對象編程 +/////////////////// + +// 有關類的第一個示例 +#include + +// 聲明一個類。 +// 類通常在頭文件(.h或.hpp)中聲明。 +class Dog { + // 成員變量和成員函數默認情況下是私有(private)的。 + std::string name; + int weight; + +// 在這個標籤之後,所有聲明都是公有(public)的, +// 直到重新指定“private:”(私有繼承)或“protected:”(保護繼承)爲止 +public: + + // 默認的構造器 + Dog(); + + // Member function declarations (implementations to follow) + // Note that we use std::string here instead of placing + // using namespace std; + // above. + // Never put a "using namespace" statement in a header. + void setName(const std::string& dogsName); + + void setWeight(int dogsWeight); + + // Functions that do not modify the state of the object + // should be marked as const. + // This allows you to call them if given a const reference to the object. + // Also note the functions must be explicitly declared as _virtual_ + // in order to be overridden in derived classes. + // Functions are not virtual by default for performance reasons. + virtual void print() const; + + // 函數也可以在class body內部定義。 + // 這樣定義的函數會自動成爲內聯函數。 + void bark() const { std::cout << name << " barks!\n" } + + // 除了構造器以外,C++還提供了析構器。 + // These are called when an object is deleted or falls out of scope. + // 這使得如同下文中的RAII這樣的強大範式成爲可能。 + // Destructors must be virtual to allow classes to be derived from this one. + virtual ~Dog(); + +}; // 在類的定義後必須加一個分號 + +// 類的成員函數通常在.cpp文件中實現。 +void Dog::Dog() +{ + std::cout << "A dog has been constructed\n"; +} + +// 對象(例如字符串)應當以引用的形式傳遞, +// 不需要修改的對象則應當作爲【const ref】。 +void Dog::setName(const std::string& dogsName) +{ + name = dogsName; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// Notice that "virtual" is only needed in the declaration, not the definition. +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +int main() { + Dog myDog; // 此時顯示“A dog has been constructed” + myDog.setName("Barkley"); + myDog.setWeight(10); + myDog.printDog(); // 顯示“Dog is Barkley and weighs 10 kg” + return 0; +} // 顯示“Goodbye Barkley” + +// 繼承: + +// 這個類繼承了Dog類中的公有(public)和保護(protected)對象 +class OwnedDog : public Dog { + + void setOwner(const std::string& dogsOwner) + + // 重寫OwnedDogs類的print方法。 + // 如果你不熟悉子類多態的話,可以參考這個頁面中的概述: + // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + + // override關鍵字是可選的,它確保你是在重寫基類中的方法。 + void print() const override; + +private: + std::string owner; +}; + +// 與此同時,在對應的.cpp文件裏: + +void OwnedDog::setOwner(const std::string& dogsOwner) +{ + owner = dogsOwner; +} + +void OwnedDog::print() const +{ + Dog::print(); // 調用基類Dog中的print方法 + // "Dog is and weights " + + std::cout << "Dog is owned by " << owner << "\n"; + // "Dog is owned by " +} + +///////////////////// +// 初始化與運算符重載 +///////////////////// + +// 在C++中,你可以重載+、-、*、/等運算符的行爲。 +// This is done by defining a function +// which is called whenever the operator is used. + +#include +using namespace std; + +class Point { +public: + // 可以以這樣的方式爲成員變量設置默認值。 + double x = 0; + double y = 0; + + // Define a default constructor which does nothing + // but initialize the Point to the default value (0, 0) + 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) : + x(a), + y(b) + { /* Do nothing except initialize the values */ } + + // 重載 + 運算符 + Point operator+(const Point& rhs) const; + + // 重載 += 運算符 + Point& operator+=(const Point& rhs); + + // 增加 - 和 -= 運算符也是有意義的,這裏不再贅述。 +}; + +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); +} + +Point& Point::operator+=(const Point& rhs) +{ + x += rhs.x; + y += rhs.y; + return *this; +} + +int main () { + Point up (0,1); + Point right (1,0); + // 這裏調用了Point類型的運算符“+” + // 調用up(Point類型)的“+”方法,並以right作爲函數的參數 + Point result = up + right; + // 顯示“Result is upright (1,1)” + cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; + return 0; +} + +/////////// +// 異常處理 +/////////// + +// 標準庫中提供了a few exception types +// (參見http://en.cppreference.com/w/cpp/error/exception) +// but any type can be thrown an as exception +#include + +// All exceptions thrown inside the _try_ block can be caught by subsequent +// _catch_ handlers. +try { + // Do not allocate exceptions on the heap using _new_. + throw std::exception("A problem occurred"); +} +// Catch exceptions by const reference if they are objects +catch (const std::exception& ex) +{ + std::cout << ex.what(); +// Catches any exception not caught by previous _catch_ blocks +} catch (...) +{ + std::cout << "Unknown exception caught"; + throw; // Re-throws the exception +} + +/////// +// RAII +/////// + +// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization)。 +// It is often considered the most powerful paradigm in C++, +// and is the simple concept that a constructor for an object +// acquires that object's resources and the destructor releases them. + +// 爲了理解這一範式的用處,讓我們考慮某個函數使用文件句柄時的情況: +void doSomethingWithAFile(const char* filename) +{ + // 首先,讓我們假設一切都會順利進行。 + + FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + + fclose(fh); // 關閉文件句柄 +} + +// 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜。 +// 假設fopen有可能執行失敗, +// 而doSomethingWithTheFile和doSomethingElseWithIt會在失敗時返回錯誤代碼。 +// (雖然【Exceptions】是處理錯誤的推薦方式, +// 但是某些程序員,尤其是有C語言背景的,並不認可【exceptions】的效用)。 +// 現在,我們必須檢查每個函數調用是否成功執行,並在問題發生的時候關閉文件句柄。 +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + if (fh == nullptr) // 當執行失敗是,返回的指針是nullptr + return false; // 向調用者彙報錯誤 + + // 假設每個函數會在執行失敗時返回false + if (!doSomethingWithTheFile(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // 反饋錯誤 + } + if (!doSomethingElseWithIt(fh)) { + fclose(fh); // Close the file handle so it doesn't leak. + return false; // 反饋錯誤 + } + + fclose(fh); // Close the file handle so it doesn't leak. + return true; // 指示函數已成功執行 +} + +// C語言的程序員通常會借助goto語句簡化上面的代碼: +bool doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); + if (fh == nullptr) + return false; + + if (!doSomethingWithTheFile(fh)) + goto failure; + + if (!doSomethingElseWithIt(fh)) + goto failure; + + fclose(fh); // 關閉文件 + return true; // 執行成功 + +failure: + fclose(fh); + return false; // 反饋錯誤 +} + +// If the functions indicate errors using exceptions, +// things are a little cleaner, but still sub-optimal. +void doSomethingWithAFile(const char* filename) +{ + FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + if (fh == nullptr) + throw std::exception("Could not open the file."); + + try { + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + } + catch (...) { + fclose(fh); // 保證出錯的時候文件被正確關閉 + throw; // Then re-throw the exception. + } + + fclose(fh); // 關閉文件 + // 所有工作順利完成 +} + +// Compare this to the use of C++'s file stream class (fstream) +// fstream利用自己的析構器來關閉文件句柄。 +// Recall from above that destructors are automatically called +// whenver an object falls out of scope. +void doSomethingWithAFile(const std::string& filename) +{ + // ifstream is short for input file stream + std::ifstream fh(filename); // Open the file + + // 對文件進行一些操作 + doSomethingWithTheFile(fh); + doSomethingElseWithIt(fh); + +} // 文件已經被析構器自動關閉 + +// 與上面幾種方式相比,這種方式有着_明顯_的優勢: +// 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 +// 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 +// 2. Note that the code is much cleaner. +// The destructor handles closing the file behind the scenes +// without you having to worry about it. +// 3. The code is exception safe. +// An exception can be thrown anywhere in the function and cleanup +// will still occur. + +// All idiomatic C++ code uses RAII extensively for all resources. +// Additional examples include +// - Memory using unique_ptr and shared_ptr +// - Containers - the standard library linked list, +// vector (i.e. self-resizing array), hash maps, and so on +// all automatically destroy their contents when they fall out of scope. +// - Mutexes using lock_guard and unique_lock +``` +擴展閱讀: + + 提供了最新的語法參考。 + +可以在 找到一些補充資料。 -- cgit v1.2.3 From b3d7a178e729c142eb6890a815c13137d4d35314 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 14 Mar 2015 13:16:34 +0800 Subject: [c++/cn] mark all parts still in progress. --- zh-cn/c++-cn.html.markdown | 117 ++++++++++++++++++++++----------------------- 1 file changed, 57 insertions(+), 60 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index f1bdf158..9a952d85 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -39,7 +39,7 @@ int main(int argc, char** argv) { // 和C語言一樣,命令行參數通過argc和argv傳遞。 // argc代表命令行參數的數量, - // 而argv是一個包含“C語言風格字符串”(char *)的數組, + // 而argv是一個包含「C語言風格字符串」(char *)的數組, // 其中每個字符串代表一個命令行參數的內容, // 首個命令行參數是調用該程序時所使用的名稱。 // 如果你不關心命令行參數的值,argc和argv可以被忽略。 @@ -68,7 +68,7 @@ void func(); // 這個函數能接受任意數量的參數 int* ip = nullptr; // C++也可以使用C語言的標準頭文件, -// 但是需要加上前綴“c”並去掉末尾的“.h”。 +// 但是需要加上前綴「c」並去掉末尾的「.h」。 #include int main() @@ -81,7 +81,7 @@ int main() // 函數重載 /////////// -// C++支持函數重載,provided each function takes different parameters. +// C++支持函數重載,【provided each function takes different parameters.】 void print(char const* myString) { @@ -138,8 +138,8 @@ namespace First { { printf("This is First::Nested::foo\n"); } - } // end namespace Nested -} // end namespace First + } // 結束嵌套的命名空間Nested +} // 結束命名空間First namespace Second { void foo() @@ -155,23 +155,23 @@ void foo() int main() { - // 如果沒有特別指定,所有【對象】都使用【取自】"Second"中的【聲明】。 + // 如果沒有特別指定,就從「Second」中取得所需的內容。 using namespace Second; - foo(); // 顯示 "This is Second::foo" - First::Nested::foo(); // 顯示 "This is First::Nested::foo" - ::foo(); // 顯示 "This is global foo" + foo(); // 顯示「This is Second::foo」 + First::Nested::foo(); // 顯示「This is First::Nested::foo」 + ::foo(); // 顯示「This is global foo」 } //////////// // 輸入/輸出 //////////// -// C++使用“流”來輸入輸出。 +// C++使用「流」來輸入輸出。 // cin、cout、和cerr分別代表stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 // <<是流的插入運算符,>>是流提取運算符。 -#include // Include for I/O streams +#include // 引入包含輸入/輸出流的頭文件 using namespace std; // 輸入輸出流在std命名空間(也就是標準庫)中。 @@ -184,9 +184,9 @@ int main() // 從標準輸入(鍵盤)獲得一個值 cin >> myInt; - // cout can also be formatted + // cout也提供了格式化功能 cout << "Your favorite number is " << myInt << "\n"; - // 顯示 "Your favorite number is " + // 顯示「Your favorite number is 」 cerr << "Used for error messages"; } @@ -208,7 +208,7 @@ cout << myString + myOtherString; // "Hello World" cout << myString + " You"; // "Hello You" -// C++中的字符串是可變的,具有“值語義”。 +// C++中的字符串是可變的,具有「值語義」。 myString.append(" Dog"); cout << myString; // "Hello Dog" @@ -218,7 +218,7 @@ cout << myString; // "Hello Dog" ///////////// // 除了支持C語言中的指針類型以外,C++還提供了_引用_。 -// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且引用不能被設置爲空值。 +// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且不能被設置爲空值。 // 使用引用時的語法與原變量相同: // 也就是說,對引用類型進行解引用時,不需要使用*; // 賦值時也不需要用&來取地址。 @@ -233,7 +233,7 @@ string& fooRef = foo; // 建立了一個對foo的引用。 fooRef += ". Hi!"; // 通過引用來修改foo的值 cout << fooRef; // "I am foo. Hi!" -// 這句話的並不會改變fooRef的指向,其效果與“foo = bar”相同。 +// 這句話的並不會改變fooRef的指向,其效果與「foo = bar」相同。 // 也就是說,在執行這條語句之後,foo == "I am bar"。 fooRef = bar; @@ -256,13 +256,13 @@ class Dog { int weight; // 在這個標籤之後,所有聲明都是公有(public)的, -// 直到重新指定“private:”(私有繼承)或“protected:”(保護繼承)爲止 +// 直到重新指定「private:」(私有繼承)或「protected:」(保護繼承)爲止 public: // 默認的構造器 Dog(); - // Member function declarations (implementations to follow) + // 【Member function declarations (implementations to follow) // Note that we use std::string here instead of placing // using namespace std; // above. @@ -271,7 +271,7 @@ public: void setWeight(int dogsWeight); - // Functions that do not modify the state of the object + // 【Functions that do not modify the state of the object // should be marked as const. // This allows you to call them if given a const reference to the object. // Also note the functions must be explicitly declared as _virtual_ @@ -284,12 +284,12 @@ public: void bark() const { std::cout << name << " barks!\n" } // 除了構造器以外,C++還提供了析構器。 - // These are called when an object is deleted or falls out of scope. - // 這使得如同下文中的RAII這樣的強大範式成爲可能。 - // Destructors must be virtual to allow classes to be derived from this one. + // 當一個對象被刪除或者【falls out of scope】時,它的析構器會被調用。 + // 這使得RAII這樣的強大範式(參見下文)成爲可能。 + // 析構器【must be virtual to allow classes to be derived from this one. virtual ~Dog(); -}; // 在類的定義後必須加一個分號 +}; // 在類的定義之後,要加一個分號 // 類的成員函數通常在.cpp文件中實現。 void Dog::Dog() @@ -309,7 +309,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// Notice that "virtual" is only needed in the declaration, not the definition. +// 【Notice that "virtual" is only needed in the declaration, not the definition. void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -321,12 +321,12 @@ void Dog::~Dog() } int main() { - Dog myDog; // 此時顯示“A dog has been constructed” + Dog myDog; // 此時顯示「A dog has been constructed」 myDog.setName("Barkley"); myDog.setWeight(10); - myDog.printDog(); // 顯示“Dog is Barkley and weighs 10 kg” + myDog.printDog(); // 顯示「Dog is Barkley and weighs 10 kg」 return 0; -} // 顯示“Goodbye Barkley” +} // 顯示「Goodbye Barkley」 // 繼承: @@ -367,7 +367,7 @@ void OwnedDog::print() const ///////////////////// // 在C++中,你可以重載+、-、*、/等運算符的行爲。 -// This is done by defining a function +// 【This is done by defining a function // which is called whenever the operator is used. #include @@ -379,16 +379,16 @@ public: double x = 0; double y = 0; - // Define a default constructor which does nothing + // 【Define a default constructor which does nothing // but initialize the Point to the default value (0, 0) Point() { }; - // The following syntax is known as an initialization list + // 【The following syntax is known as an initialization list // and is the proper way to initialize class member values Point (double a, double b) : x(a), y(b) - { /* Do nothing except initialize the values */ } + { /* 【Do nothing except initialize the values */ } // 重載 + 運算符 Point operator+(const Point& rhs) const; @@ -401,7 +401,7 @@ public: Point Point::operator+(const Point& rhs) const { - // Create a new point that is the sum of this one and rhs. + // 【Create a new point that is the sum of this one and rhs. return Point(x + rhs.x, y + rhs.y); } @@ -415,10 +415,10 @@ Point& Point::operator+=(const Point& rhs) int main () { Point up (0,1); Point right (1,0); - // 這裏調用了Point類型的運算符“+” - // 調用up(Point類型)的“+”方法,並以right作爲函數的參數 + // 這裏調用了Point類型的運算符「+」 + // 調用up(Point類型)的「+」方法,並以right作爲函數的參數 Point result = up + right; - // 顯示“Result is upright (1,1)” + // 顯示「Result is upright (1,1)」 cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } @@ -429,32 +429,31 @@ int main () { // 標準庫中提供了a few exception types // (參見http://en.cppreference.com/w/cpp/error/exception) -// but any type can be thrown an as exception +// 【but any type can be thrown an as exception #include -// All exceptions thrown inside the _try_ block can be caught by subsequent -// _catch_ handlers. +// 在_try_代碼塊中拋出的異常可以被隨後的_catch_捕獲。 try { - // Do not allocate exceptions on the heap using _new_. + // 【Do not allocate exceptions on the heap using _new_. throw std::exception("A problem occurred"); } -// Catch exceptions by const reference if they are objects +// 【Catch exceptions by const reference if they are objects catch (const std::exception& ex) { std::cout << ex.what(); -// Catches any exception not caught by previous _catch_ blocks +// 捕獲尚未被_catch_處理的所有錯誤 } catch (...) { std::cout << "Unknown exception caught"; - throw; // Re-throws the exception + throw; // 重新拋出異常 } /////// // RAII /////// -// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization)。 -// It is often considered the most powerful paradigm in C++, +// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization)。 +// 【It is often considered the most powerful paradigm in C++, // and is the simple concept that a constructor for an object // acquires that object's resources and the destructor releases them. @@ -472,10 +471,10 @@ void doSomethingWithAFile(const char* filename) } // 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜。 -// 假設fopen有可能執行失敗, +// 假設fopen函數有可能執行失敗, // 而doSomethingWithTheFile和doSomethingElseWithIt會在失敗時返回錯誤代碼。 -// (雖然【Exceptions】是處理錯誤的推薦方式, -// 但是某些程序員,尤其是有C語言背景的,並不認可【exceptions】的效用)。 +// (雖然異常是C++中處理錯誤的推薦方式, +// 但是某些程序員,尤其是有C語言背景的,並不認可異常捕獲機制的作用)。 // 現在,我們必須檢查每個函數調用是否成功執行,並在問題發生的時候關閉文件句柄。 bool doSomethingWithAFile(const char* filename) { @@ -518,7 +517,7 @@ failure: return false; // 反饋錯誤 } -// If the functions indicate errors using exceptions, +// 【If the functions indicate errors using exceptions, // things are a little cleaner, but still sub-optimal. void doSomethingWithAFile(const char* filename) { @@ -539,13 +538,13 @@ void doSomethingWithAFile(const char* filename) // 所有工作順利完成 } -// Compare this to the use of C++'s file stream class (fstream) +// 【Compare this to the use of C++'s file stream class (fstream) // fstream利用自己的析構器來關閉文件句柄。 -// Recall from above that destructors are automatically called +// 【Recall from above that destructors are automatically called // whenver an object falls out of scope. void doSomethingWithAFile(const std::string& filename) { - // ifstream is short for input file stream + // ifstream是輸入文件流(input file stream)的簡稱 std::ifstream fh(filename); // Open the file // 對文件進行一些操作 @@ -557,20 +556,18 @@ void doSomethingWithAFile(const std::string& filename) // 與上面幾種方式相比,這種方式有着_明顯_的優勢: // 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 // 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 -// 2. Note that the code is much cleaner. +// 2. 【Note that the code is much cleaner. // The destructor handles closing the file behind the scenes // without you having to worry about it. -// 3. The code is exception safe. +// 3. 【The code is exception safe. // An exception can be thrown anywhere in the function and cleanup // will still occur. -// All idiomatic C++ code uses RAII extensively for all resources. -// Additional examples include -// - Memory using unique_ptr and shared_ptr -// - Containers - the standard library linked list, -// vector (i.e. self-resizing array), hash maps, and so on -// all automatically destroy their contents when they fall out of scope. -// - Mutexes using lock_guard and unique_lock +// 地道的C++代碼應當把RAII的使用擴展到所有類型的資源上,包括: +// - 用unique_ptr和shared_ptr管理的內存 +// - 容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; +// 【all automatically destroy their contents when they fall out of scope. +// - 用lock_guard和unique_lock實現的互斥 ``` 擴展閱讀: -- cgit v1.2.3 From cfb4d5922d485f68b9ed3ba7a9e2f1add14cba3c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Thu, 19 Mar 2015 00:31:33 +0800 Subject: Complete most parts of translation. --- zh-cn/c++-cn.html.markdown | 92 ++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 39 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 9a952d85..24d2a1b8 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -167,9 +167,9 @@ int main() // 輸入/輸出 //////////// -// C++使用「流」來輸入輸出。 -// cin、cout、和cerr分別代表stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 -// <<是流的插入運算符,>>是流提取運算符。 +// C++使用「流」來輸入輸出。<<是流的插入運算符,>>是流提取運算符。 +// cin、cout、和cerr分別代表 +// stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 #include // 引入包含輸入/輸出流的頭文件 @@ -237,9 +237,9 @@ cout << fooRef; // "I am foo. Hi!" // 也就是說,在執行這條語句之後,foo == "I am bar"。 fooRef = bar; -const string& barRef = bar; // 建立指向bar的【const ref】。 -// 和C語言中一樣,聲明爲常數的值(包括指針和引用)不能被修改。 -barRef += ". Hi!"; // 這是錯誤的,【const ref】不能被修改。 +const string& barRef = bar; // 建立指向bar的常量引用。 +// 和C語言中一樣,(指針和引用)聲明爲常量時,對應的值不能被修改。 +barRef += ". Hi!"; // 這是錯誤的,不能修改一個常量引用的值。 /////////////////// // 類與面向對象編程 @@ -262,21 +262,19 @@ public: // 默認的構造器 Dog(); - // 【Member function declarations (implementations to follow) - // Note that we use std::string here instead of placing - // using namespace std; - // above. - // Never put a "using namespace" statement in a header. + // 這裏是成員函數聲明的一個例子。 + // 可以注意到,我們在此處使用了std::string,而不是using namespace std + // 語句using namespace絕不應當出現在頭文件當中。 void setName(const std::string& dogsName); void setWeight(int dogsWeight); - // 【Functions that do not modify the state of the object - // should be marked as const. - // This allows you to call them if given a const reference to the object. - // Also note the functions must be explicitly declared as _virtual_ - // in order to be overridden in derived classes. - // Functions are not virtual by default for performance reasons. + // 如果一個函數不對對象的狀態進行修改, + // 應當在聲明中加上const。 + // 這樣,你就可以對一個以常量方式引用的對象執行該操作。 + // 同時可以注意到,當父類的成員函數需要被子類重寫時, + // 父類中的函數必須被顯式聲明爲_虛函數(virtual)_。 + // 考慮到性能方面的因素,函數默認情況下不會被聲明爲虛函數。 virtual void print() const; // 函數也可以在class body內部定義。 @@ -284,13 +282,15 @@ public: void bark() const { std::cout << name << " barks!\n" } // 除了構造器以外,C++還提供了析構器。 - // 當一個對象被刪除或者【falls out of scope】時,它的析構器會被調用。 + // 當一個對象被刪除或者脫離其定義域時時,它的析構函數會被調用。 // 這使得RAII這樣的強大範式(參見下文)成爲可能。 - // 析構器【must be virtual to allow classes to be derived from this one. + // 爲了衍生出子類來,基類的析構函數必須定義爲虛函數。 virtual ~Dog(); }; // 在類的定義之後,要加一個分號 +}; // 記住,在類的定義之後,要加一個分號! + // 類的成員函數通常在.cpp文件中實現。 void Dog::Dog() { @@ -298,7 +298,7 @@ void Dog::Dog() } // 對象(例如字符串)應當以引用的形式傳遞, -// 不需要修改的對象則應當作爲【const ref】。 +// 對於不需要修改的對象,最好使用常量引用。 void Dog::setName(const std::string& dogsName) { name = dogsName; @@ -309,7 +309,23 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 【Notice that "virtual" is only needed in the declaration, not the definition. +// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時出現 +void Dog::print() const +{ + std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; +} + +void Dog::~Dog() +{ + cout << "Goodbye " << name << "\n"; +} + +void Dog::setWeight(int dogsWeight) +{ + weight = dogsWeight; +} + +// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時重複 void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -427,17 +443,17 @@ int main () { // 異常處理 /////////// -// 標準庫中提供了a few exception types +// 標準庫中提供了一些基本的異常類型 // (參見http://en.cppreference.com/w/cpp/error/exception) -// 【but any type can be thrown an as exception +// 但是,其他任何類型也可以作爲一個異常被拋出 #include // 在_try_代碼塊中拋出的異常可以被隨後的_catch_捕獲。 try { - // 【Do not allocate exceptions on the heap using _new_. + // 不要用 _new_關鍵字在堆上爲異常分配空間。 throw std::exception("A problem occurred"); } -// 【Catch exceptions by const reference if they are objects +// 如果拋出的異常是一個對象,可以用常量引用來捕獲它 catch (const std::exception& ex) { std::cout << ex.what(); @@ -452,10 +468,10 @@ catch (const std::exception& ex) // RAII /////// -// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization)。 -// 【It is often considered the most powerful paradigm in C++, -// and is the simple concept that a constructor for an object -// acquires that object's resources and the destructor releases them. +// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization), +// 它被視作C++中最強大的編程範式之一。 +// 簡單說來,它指的是,用構造函數來獲取一個對象的資源, +// 相應的,借助析構函數來釋放對象的資源。 // 爲了理解這一範式的用處,讓我們考慮某個函數使用文件句柄時的情況: void doSomethingWithAFile(const char* filename) @@ -517,8 +533,8 @@ failure: return false; // 反饋錯誤 } -// 【If the functions indicate errors using exceptions, -// things are a little cleaner, but still sub-optimal. +// 如果用異常捕獲機制來指示錯誤的話, +// 代碼會變得清晰一些,但是仍然有優化的餘地。 void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 @@ -556,17 +572,15 @@ void doSomethingWithAFile(const std::string& filename) // 與上面幾種方式相比,這種方式有着_明顯_的優勢: // 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 // 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 -// 2. 【Note that the code is much cleaner. -// The destructor handles closing the file behind the scenes -// without you having to worry about it. +// 2. 可以注意到,通過這種方式寫出來的代碼十分簡潔。 +// 析構器會在後臺關閉文件句柄,不再需要你來操心這些瑣事。 // 3. 【The code is exception safe. -// An exception can be thrown anywhere in the function and cleanup -// will still occur. +// 無論在函數中的何處拋出異常,都不會阻礙對文件資源的釋放。 -// 地道的C++代碼應當把RAII的使用擴展到所有類型的資源上,包括: +// 地道的C++代碼應當把RAII的使用擴展到各種類型的資源上,包括: // - 用unique_ptr和shared_ptr管理的內存 -// - 容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; -// 【all automatically destroy their contents when they fall out of scope. +// - 各種數據容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; +// 當它們脫離作用域時,析構器會自動釋放其中儲存的內容。 // - 用lock_guard和unique_lock實現的互斥 ``` 擴展閱讀: -- cgit v1.2.3 From cfe726561dd27cf74aaf966eae4cf6f5b5556812 Mon Sep 17 00:00:00 2001 From: yukirock Date: Thu, 19 Mar 2015 18:36:10 +1100 Subject: Improve zh-ch translation. --- zh-cn/haskell-cn.html.markdown | 234 ++++++++++++++++++++--------------------- 1 file changed, 116 insertions(+), 118 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index cb7ccdee..fae8a456 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -5,24 +5,24 @@ contributors: - ["Adit Bhargava", "http://adit.io"] translators: - ["Peiyong Lin", ""] + - ["chad luo", "http://yuki.rocks"] lang: zh-cn --- -Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads 及其类型系统而出名,但是我回归到它本身因为。Haskell 使得编程对于我而言是一种真正的快乐。 +Haskell 是一门实用的函数式编程语言,因其 Monads 与类型系统而闻名。而我使用它则是因为它异常优雅。用 Haskell 编程令我感到非常快乐。 ```haskell --- 单行注释以两个破折号开头 -{- 多行注释像这样 - 被一个闭合的块包围 +-- 单行注释以两个减号开头 +{- 多行注释像这样被一个闭合的块包围 -} ---------------------------------------------------- -- 1. 简单的数据类型和操作符 ---------------------------------------------------- --- 你有数字 +-- 数字 3 -- 3 --- 数学计算就像你所期待的那样 +-- 数学计算 1 + 1 -- 2 8 - 1 -- 7 10 * 2 -- 20 @@ -34,7 +34,7 @@ Haskell 被设计成一种实用的纯函数式编程语言。它因为 monads -- 整除 35 `div` 4 -- 8 --- 布尔值也简单 +-- 布尔值 True False @@ -45,73 +45,80 @@ not False -- True 1 /= 1 -- False 1 < 10 -- True --- 在上述的例子中,`not` 是一个接受一个值的函数。 --- Haskell 不需要括号来调用函数。。。所有的参数 --- 都只是在函数名之后列出来。因此,通常的函数调用模式是: +-- 在上面的例子中,`not` 是一个接受一个参数的函数。 +-- Haskell 不需要括号来调用函数。所有的参数都只是在函数名之后列出来。 +-- 因此,通常的函数调用模式是: -- func arg1 arg2 arg3... --- 查看关于函数的章节以获得如何写你自己的函数的相关信息。 +-- 你可以查看函数部分了解如何自行编写。 -- 字符串和字符 -"This is a string." +"This is a string." -- 字符串 'a' -- 字符 '对于字符串你不能使用单引号。' -- 错误! --- 连结字符串 +-- 连接字符串 "Hello " ++ "world!" -- "Hello world!" -- 一个字符串是一系列字符 +['H', 'e', 'l', 'l', 'o'] -- "Hello" "This is a string" !! 0 -- 'T' ---------------------------------------------------- --- 列表和元组 +-- 数组和元组 ---------------------------------------------------- --- 一个列表中的每一个元素都必须是相同的类型 --- 下面两个列表一样 +-- 一个数组中的每一个元素都必须是相同的类型 +-- 下面两个数组等价: [1, 2, 3, 4, 5] [1..5] --- 在 Haskell 你可以拥有含有无限元素的列表 -[1..] -- 一个含有所有自然数的列表 +-- 区间也可以这样 +['A'..'F'] -- "ABCDEF" --- 因为 Haskell 有“懒惰计算”,所以无限元素的列表可以正常运作。这意味着 --- Haskell 可以只在它需要的时候计算。所以你可以请求 --- 列表中的第1000个元素,Haskell 会返回给你 +-- 你可以在区间中指定步进 +[0,2..10] -- [0, 2, 4, 6, 8, 10] +[5..1] -- 这样不行,因为 Haskell 默认递增 +[5,4..1] -- [5, 4, 3, 2, 1] + +-- 数组下标 +[0..] !! 5 -- 5 + +-- 在 Haskell 你可以使用无限数组 +[1..] -- 一个含有所有自然数的数组 + +-- 无限数组的原理是,Haskell 有“惰性求值”。 +-- 这意味着 Haskell 只在需要时才会计算。 +-- 所以当你获取数组的第 1000 项元素时,Haskell 会返回给你: [1..] !! 999 -- 1000 --- Haskell 计算了列表中 1 - 1000 个元素。。。但是 --- 这个无限元素的列表中剩下的元素还不存在! Haskell 不会 --- 真正地计算它们知道它需要。 +-- Haskell 计算了数组中第 1 至 1000 项元素,但这个无限数组中剩下的元素还不存在。 +-- Haskell 只有在需要时才会计算它们。 -- 连接两个列表 +-- 连接两个数组 [1..5] ++ [6..10] --- 往列表头增加元素 +-- 往数组头增加元素 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- 列表中的下标 -[0..] !! 5 -- 5 - --- 更多列表操作 +-- 其它数组操作 head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] init [1..5] -- [1, 2, 3, 4] last [1..5] -- 5 --- 列表推导 +-- 数组推导 [x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] -- 附带条件 [x*2 | x <-[1..5], x*2 > 4] -- [6, 8, 10] --- 元组中的每一个元素可以是不同类型的,但是一个元组 --- 的长度是固定的 +-- 元组中的每一个元素可以是不同类型,但是一个元组的长度是固定的 -- 一个元组 ("haskell", 1) --- 获取元组中的元素 +-- 获取元组中的元素(例如,一个含有 2 个元素的元祖) fst ("haskell", 1) -- "haskell" snd ("haskell", 1) -- 1 @@ -121,31 +128,28 @@ snd ("haskell", 1) -- 1 -- 一个接受两个变量的简单函数 add a b = a + b --- 注意,如果你使用 ghci (Hakell 解释器) --- 你将需要使用 `let`,也就是 +-- 注意,如果你使用 ghci (Hakell 解释器),你需要使用 `let`,也就是 -- let add a b = a + b --- 使用函数 +-- 调用函数 add 1 2 -- 3 --- 你也可以把函数放置在两个参数之间 --- 附带倒引号: +-- 你也可以使用反引号中置函数名: 1 `add` 2 -- 3 --- 你也可以定义不带字符的函数!这使得 --- 你定义自己的操作符!这里有一个操作符 --- 来做整除 +-- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符 +-- 这里有一个做整除的操作符 (//) a b = a `div` b 35 // 4 -- 8 --- 守卫:一个简单的方法在函数里做分支 +-- Guard:一个在函数中做条件判断的简单方法 fib x | x < 2 = x | otherwise = fib (x - 1) + fib (x - 2) --- 模式匹配是类型的。这里有三种不同的 fib --- 定义。Haskell 将自动调用第一个 --- 匹配值的模式的函数。 +-- 模式匹配与 Guard 类似 +-- 这里给出了三个不同的 fib 定义 +-- Haskell 会自动调用第一个符合参数模式的声明 fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) @@ -153,76 +157,76 @@ fib x = fib (x - 1) + fib (x - 2) -- 元组的模式匹配: foo (x, y) = (x + 1, y + 2) --- 列表的模式匹配。这里 `x` 是列表中第一个元素, --- 并且 `xs` 是列表剩余的部分。我们可以写 --- 自己的 map 函数: +-- 数组的模式匹配 +-- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分 +-- 我们可以实现自己的 map 函数: myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) --- 编写出来的匿名函数带有一个反斜杠,后面跟着 --- 所有的参数。 +-- 匿名函数带有一个反斜杠,后面跟着所有的参数。 myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] --- 使用 fold (在一些语言称为`inject`)随着一个匿名的 --- 函数。foldl1 意味着左折叠(fold left), 并且使用列表中第一个值 --- 作为累加器的初始化值。 +-- 在 fold(在一些语言称 为`inject`)中使用匿名函数 +-- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值 foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- --- 4. 更多的函数 +-- 4. 其它函数 ---------------------------------------------------- --- 柯里化(currying):如果你不传递函数中所有的参数, --- 它就变成“柯里化的”。这意味着,它返回一个接受剩余参数的函数。 - +-- 部分调用: +-- 如果你调用函数时没有给出所有参数,它就被“部分调用” +-- 它将返回一个接受余下参数的函数 add a b = a + b foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 foo 5 -- 15 --- 另外一种方式去做同样的事 +-- 另一种等价写法 foo = (+10) foo 5 -- 15 -- 函数组合 -- (.) 函数把其它函数链接到一起 --- 举个列子,这里 foo 是一个接受一个值的函数。它对接受的值加 10, --- 并对结果乘以 5,之后返回最后的值。 +-- 例如,这里 foo 是一个接受一个值的函数。 +-- 它对接受的值加 10,并对结果乘以 5,之后返回最后的值。 foo = (*5) . (+10) -- (5 + 10) * 5 = 75 foo 5 -- 75 --- 修复优先级 --- Haskell 有另外一个函数称为 `$`。它改变优先级 --- 使得其左侧的每一个操作先计算然后应用到 --- 右侧的每一个操作。你可以使用 `.` 和 `$` 来除去很多 --- 括号: +-- 修正优先级 +-- Haskell 有另外一个函数 `$` 可以改变优先级 +-- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分 +-- 你可以使用 `$` 来移除多余的括号 --- before +-- 修改前 (even (fib 7)) -- true --- after +-- 修改后 even . fib $ 7 -- true +-- 等价地 +even $ fib 7 -- true + ---------------------------------------------------- --- 5. 类型签名 +-- 5. 类型声明 ---------------------------------------------------- --- Haskell 有一个非常强壮的类型系统,一切都有一个类型签名。 +-- Haskell 有一个非常强大的类型系统,一切都有一个类型声明。 -- 一些基本的类型: 5 :: Integer "hello" :: String True :: Bool --- 函数也有类型。 +-- 函数也有类型 -- `not` 接受一个布尔型返回一个布尔型: -- not :: Bool -> Bool -- 这是接受两个参数的函数: -- add :: Integer -> Integer -> Integer --- 当你定义一个值,在其上写明它的类型是一个好实践: +-- 当你定义一个值,声明其类型是一个好做法: double :: Integer -> Integer double x = x * 2 @@ -230,29 +234,30 @@ double x = x * 2 -- 6. 控制流和 If 语句 ---------------------------------------------------- --- if 语句 +-- if 语句: haskell = if 1 == 1 then "awesome" else "awful" -- haskell = "awesome" --- if 语句也可以有多行,缩进是很重要的 +-- if 语句也可以有多行,注意缩进: haskell = if 1 == 1 then "awesome" else "awful" --- case 语句:这里是你可以怎样去解析命令行参数 +-- case 语句 +-- 解析命令行参数: case args of "help" -> printHelp "start" -> startProgram _ -> putStrLn "bad args" --- Haskell 没有循环因为它使用递归取代之。 --- map 应用一个函数到一个数组中的每一个元素 +-- Haskell 没有循环,它使用递归 +-- map 对一个数组中的每一个元素调用一个函数: map (*2) [1..5] -- [2, 4, 6, 8, 10] --- 你可以使用 map 来编写 for 函数 +-- 你可以使用 map 来编写 for 函数: for array func = map func array --- 然后使用它 +-- 调用: for [0..5] $ \i -> show i -- 我们也可以像这样写: @@ -262,36 +267,32 @@ for [0..5] show -- foldl foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- 这和下面是一样的 +-- 等价于: (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl 是左手边的,foldr 是右手边的- +-- foldl 从左开始,foldr 从右: foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- 这和下面是一样的 +-- 现在它等价于: (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- -- 7. 数据类型 ---------------------------------------------------- --- 这里展示在 Haskell 中你怎样编写自己的数据类型 - +-- 在 Haskell 中声明你自己的数据类型: data Color = Red | Blue | Green -- 现在你可以在函数中使用它: - - say :: Color -> String say Red = "You are Red!" say Blue = "You are Blue!" say Green = "You are Green!" -- 你的数据类型也可以有参数: - data Maybe a = Nothing | Just a --- 类型 Maybe 的所有 +-- 这些都是 Maybe 类型: Just "hello" -- of type `Maybe String` Just 1 -- of type `Maybe Int` Nothing -- of type `Maybe a` for any `a` @@ -300,58 +301,54 @@ Nothing -- of type `Maybe a` for any `a` -- 8. Haskell IO ---------------------------------------------------- --- 虽然在没有解释 monads 的情况下 IO不能被完全地解释, --- 着手解释到位并不难。 - --- 当一个 Haskell 程序被执行,函数 `main` 就被调用。 --- 它必须返回一个类型 `IO ()` 的值。举个列子: +-- 虽然不解释 Monads 就无法完全解释 IO,但大致了解并不难。 +-- 当执行一个 Haskell 程序时,函数 `main` 就被调用。 +-- 它必须返回一个类型 `IO ()` 的值。例如: main :: IO () main = putStrLn $ "Hello, sky! " ++ (say Blue) --- putStrLn has type String -> IO () +-- putStrLn 的类型是 String -> IO () --- 如果你能实现你的程序依照函数从 String 到 String,那样编写 IO 是最简单的。 +-- 如果你的程序输入 String 返回 String,那样编写 IO 是最简单的。 -- 函数 -- interact :: (String -> String) -> IO () --- 输入一些文本,在其上运行一个函数,并打印出输出 +-- 输入一些文本,对其调用一个函数,并打印输出。 countLines :: String -> String countLines = show . length . lines main' = interact countLines --- 你可以考虑一个 `IO()` 类型的值,当做一系列计算机所完成的动作的代表, --- 就像一个以命令式语言编写的计算机程序。我们可以使用 `do` 符号来把动作链接到一起。 +-- 你可以认为一个 `IO ()` 类型的值是表示计算机做的一系列操作,类似命令式语言。 +-- 我们可以使用 `do` 声明来把动作连接到一起。 -- 举个列子: - sayHello :: IO () sayHello = do putStrLn "What is your name?" - name <- getLine -- this gets a line and gives it the name "input" + name <- getLine -- 这里接受一行输入并绑定至 "name" putStrLn $ "Hello, " ++ name -- 练习:编写只读取一行输入的 `interact` -- 然而,`sayHello` 中的代码将不会被执行。唯一被执行的动作是 `main` 的值。 --- 为了运行 `sayHello`,注释上面 `main` 的定义,并代替它: +-- 为了运行 `sayHello`,注释上面 `main` 的定义,替换为: -- main = sayHello --- 让我们来更好地理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: +-- 让我们来更进一步理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: -- getLine :: IO String --- 你可以考虑一个 `IO a` 类型的值,代表一个当被执行的时候 --- 将产生一个 `a` 类型的值的计算机程序(除了它所做的任何事之外)。我们可以保存和重用这个值通过 `<-`。 --- 我们也可以写自己的 `IO String` 类型的动作: - +-- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序(可能还有其它行为)。 +-- 我们可以通过 `<-` 保存和重用这个值。 +-- 我们也可以实现自己的 `IO String` 类型函数: action :: IO String action = do putStrLn "This is a line. Duh" input1 <- getLine input2 <- getLine - -- The type of the `do` statement is that of its last line. - -- `return` is not a keyword, but merely a function + -- `do` 语句的类型是它的最后一行 + -- `return` 不是关键字,只是一个普通函数 return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- 我们可以使用这个动作就像我们使用 `getLine`: +-- 我们可以像调用 `getLine` 一样调用它: main'' = do putStrLn "I will echo two lines!" @@ -359,18 +356,19 @@ main'' = do putStrLn result putStrLn "This was all, folks!" --- `IO` 类型是一个 "monad" 的例子。Haskell 使用一个 monad 来做 IO的方式允许它是一门纯函数式语言。 --- 任何与外界交互的函数(也就是 IO) 都在它的类型签名处做一个 `IO` 标志 --- 着让我们推出 什么样的函数是“纯洁的”(不与外界交互,不修改状态) 和 什么样的函数不是 “纯洁的” +-- `IO` 类型是一个 "Monad" 的例子。 +-- Haskell 通过使用 Monad 使得其本身为纯函数式语言。 +-- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO` +-- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) ,什么样的函数不是 “纯洁的” --- 这是一个强有力的特征,因为并发地运行纯函数是简单的;因此,Haskell 中并发是非常简单的。 +-- 这个功能非常强大,因为纯函数并发非常容易,由此在 Haskell 中做并发非常容易。 ---------------------------------------------------- --- 9. The Haskell REPL +-- 9. Haskell REPL ---------------------------------------------------- --- 键入 `ghci` 开始 repl。 +-- 键入 `ghci` 开始 REPL。 -- 现在你可以键入 Haskell 代码。 -- 任何新值都需要通过 `let` 来创建: @@ -390,7 +388,7 @@ Hello, Friend! ``` -还有很多关于 Haskell,包括类型类和 monads。这些是使得编码 Haskell 是如此有趣的主意。我用一个最后的 Haskell 例子来结束:一个 Haskell 的快排实现: +Haskell 还有许多内容,包括类型类 (typeclasses) 与 Monads。这些都是令 Haskell 编程非常有趣的好东西。我们最后给出 Haskell 的一个例子,一个快速排序的实现: ```haskell qsort [] = [] @@ -399,9 +397,9 @@ qsort (p:xs) = qsort lesser ++ [p] ++ qsort greater greater = filter (>= p) xs ``` -安装 Haskell 是简单的。你可以从[这里](http://www.haskell.org/platform/)获得它。 +安装 Haskell 很简单。你可以[从这里获得](http://www.haskell.org/platform/)。 你可以从优秀的 [Learn you a Haskell](http://learnyouahaskell.com/) 或者 [Real World Haskell](http://book.realworldhaskell.org/) -找到优雅不少的入门介绍。 +找到更平缓的入门介绍。 -- cgit v1.2.3 From f94fd7356adcf034f97256d2ce575f240a50d4b8 Mon Sep 17 00:00:00 2001 From: chadluo Date: Mon, 23 Mar 2015 01:54:46 +1100 Subject: fixed translation --- zh-cn/haskell-cn.html.markdown | 117 ++++++++++++++++++++--------------------- 1 file changed, 56 insertions(+), 61 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/haskell-cn.html.markdown b/zh-cn/haskell-cn.html.markdown index fae8a456..8904970f 100644 --- a/zh-cn/haskell-cn.html.markdown +++ b/zh-cn/haskell-cn.html.markdown @@ -13,7 +13,8 @@ Haskell 是一门实用的函数式编程语言,因其 Monads 与类型系统 ```haskell -- 单行注释以两个减号开头 -{- 多行注释像这样被一个闭合的块包围 +{- 多行注释像这样 + 被一个闭合的块包围 -} ---------------------------------------------------- @@ -46,9 +47,9 @@ not False -- True 1 < 10 -- True -- 在上面的例子中,`not` 是一个接受一个参数的函数。 --- Haskell 不需要括号来调用函数。所有的参数都只是在函数名之后列出来。 +-- Haskell 不需要括号来调用函数,所有的参数都只是在函数名之后列出来 -- 因此,通常的函数调用模式是: --- func arg1 arg2 arg3... +-- func arg1 arg2 arg3... -- 你可以查看函数部分了解如何自行编写。 -- 字符串和字符 @@ -65,11 +66,11 @@ not False -- True ---------------------------------------------------- --- 数组和元组 +-- 列表和元组 ---------------------------------------------------- --- 一个数组中的每一个元素都必须是相同的类型 --- 下面两个数组等价: +-- 一个列表中的每一个元素都必须是相同的类型。 +-- 下面两个列表等价 [1, 2, 3, 4, 5] [1..5] @@ -81,34 +82,32 @@ not False -- True [5..1] -- 这样不行,因为 Haskell 默认递增 [5,4..1] -- [5, 4, 3, 2, 1] --- 数组下标 +-- 列表下标 [0..] !! 5 -- 5 --- 在 Haskell 你可以使用无限数组 -[1..] -- 一个含有所有自然数的数组 +-- 在 Haskell 你可以使用无限列表 +[1..] -- 一个含有所有自然数的列表 --- 无限数组的原理是,Haskell 有“惰性求值”。 +-- 无限列表的原理是,Haskell 有“惰性求值”。 -- 这意味着 Haskell 只在需要时才会计算。 --- 所以当你获取数组的第 1000 项元素时,Haskell 会返回给你: - +-- 所以当你获取列表的第 1000 项元素时,Haskell 会返回给你: [1..] !! 999 -- 1000 - --- Haskell 计算了数组中第 1 至 1000 项元素,但这个无限数组中剩下的元素还不存在。 +-- Haskell 计算了列表中第 1 至 1000 项元素,但这个无限列表中剩下的元素还不存在。 -- Haskell 只有在需要时才会计算它们。 --- 连接两个数组 +-- 连接两个列表 [1..5] ++ [6..10] --- 往数组头增加元素 +-- 往列表头增加元素 0:[1..5] -- [0, 1, 2, 3, 4, 5] --- 其它数组操作 +-- 其它列表操作 head [1..5] -- 1 tail [1..5] -- [2, 3, 4, 5] init [1..5] -- [1, 2, 3, 4] last [1..5] -- 5 --- 数组推导 +-- 列表推导 (list comprehension) [x*2 | x <- [1..5]] -- [2, 4, 6, 8, 10] -- 附带条件 @@ -125,6 +124,7 @@ snd ("haskell", 1) -- 1 ---------------------------------------------------- -- 3. 函数 ---------------------------------------------------- + -- 一个接受两个变量的简单函数 add a b = a + b @@ -137,7 +137,7 @@ add 1 2 -- 3 -- 你也可以使用反引号中置函数名: 1 `add` 2 -- 3 --- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符 +-- 你也可以定义不带字母的函数名,这样你可以定义自己的操作符。 -- 这里有一个做整除的操作符 (//) a b = a `div` b 35 // 4 -- 8 @@ -147,36 +147,36 @@ fib x | x < 2 = x | otherwise = fib (x - 1) + fib (x - 2) --- 模式匹配与 Guard 类似 --- 这里给出了三个不同的 fib 定义 +-- 模式匹配与 Guard 类似。 +-- 这里给出了三个不同的 fib 定义。 -- Haskell 会自动调用第一个符合参数模式的声明 fib 1 = 1 fib 2 = 2 fib x = fib (x - 1) + fib (x - 2) --- 元组的模式匹配: +-- 元组的模式匹配 foo (x, y) = (x + 1, y + 2) --- 数组的模式匹配 --- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分 +-- 列表的模式匹配 +-- 这里 `x` 是列表中第一个元素,`xs` 是列表剩余的部分。 -- 我们可以实现自己的 map 函数: myMap func [] = [] myMap func (x:xs) = func x:(myMap func xs) --- 匿名函数带有一个反斜杠,后面跟着所有的参数。 +-- 匿名函数带有一个反斜杠,后面跟着所有的参数 myMap (\x -> x + 2) [1..5] -- [3, 4, 5, 6, 7] -- 在 fold(在一些语言称 为`inject`)中使用匿名函数 --- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值 +-- foldl1 意味着左折叠 (fold left), 并且使用列表中第一个值作为累加器的初始值。 foldl1 (\acc x -> acc + x) [1..5] -- 15 ---------------------------------------------------- -- 4. 其它函数 ---------------------------------------------------- --- 部分调用: --- 如果你调用函数时没有给出所有参数,它就被“部分调用” --- 它将返回一个接受余下参数的函数 +-- 部分调用 +-- 如果你调用函数时没有给出所有参数,它就被“部分调用”。 +-- 它将返回一个接受余下参数的函数。 add a b = a + b foo = add 10 -- foo 现在是一个接受一个数并对其加 10 的函数 foo 5 -- 15 @@ -185,8 +185,8 @@ foo 5 -- 15 foo = (+10) foo 5 -- 15 --- 函数组合 --- (.) 函数把其它函数链接到一起 +-- 函列表合 +-- (.) 函数把其它函数链接到一起。 -- 例如,这里 foo 是一个接受一个值的函数。 -- 它对接受的值加 10,并对结果乘以 5,之后返回最后的值。 foo = (*5) . (+10) @@ -195,9 +195,9 @@ foo = (*5) . (+10) foo 5 -- 75 -- 修正优先级 --- Haskell 有另外一个函数 `$` 可以改变优先级 --- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分 --- 你可以使用 `$` 来移除多余的括号 +-- Haskell 有另外一个函数 `$` 可以改变优先级。 +-- `$` 使得 Haskell 先计算其右边的部分,然后调用左边的部分。 +-- 你可以使用 `$` 来移除多余的括号。 -- 修改前 (even (fib 7)) -- true @@ -220,13 +220,13 @@ even $ fib 7 -- true True :: Bool -- 函数也有类型 --- `not` 接受一个布尔型返回一个布尔型: +-- `not` 接受一个布尔型返回一个布尔型 -- not :: Bool -> Bool --- 这是接受两个参数的函数: +-- 这是接受两个参数的函数 -- add :: Integer -> Integer -> Integer --- 当你定义一个值,声明其类型是一个好做法: +-- 当你定义一个值,声明其类型是一个好做法 double :: Integer -> Integer double x = x * 2 @@ -250,30 +250,29 @@ case args of _ -> putStrLn "bad args" -- Haskell 没有循环,它使用递归 --- map 对一个数组中的每一个元素调用一个函数: - +-- map 对一个列表中的每一个元素调用一个函数 map (*2) [1..5] -- [2, 4, 6, 8, 10] --- 你可以使用 map 来编写 for 函数: +-- 你可以使用 map 来编写 for 函数 for array func = map func array --- 调用: +-- 调用 for [0..5] $ \i -> show i --- 我们也可以像这样写: +-- 我们也可以像这样写 for [0..5] show -- 你可以使用 foldl 或者 foldr 来分解列表 -- foldl foldl (\x y -> 2*x + y) 4 [1,2,3] -- 43 --- 等价于: +-- 等价于 (2 * (2 * (2 * 4 + 1) + 2) + 3) --- foldl 从左开始,foldr 从右: +-- foldl 从左开始,foldr 从右 foldr (\x y -> 2*x + y) 4 [1,2,3] -- 16 --- 现在它等价于: +-- 现在它等价于 (2 * 3 + (2 * 2 + (2 * 1 + 4))) ---------------------------------------------------- @@ -293,9 +292,9 @@ say Green = "You are Green!" data Maybe a = Nothing | Just a -- 这些都是 Maybe 类型: -Just "hello" -- of type `Maybe String` -Just 1 -- of type `Maybe Int` -Nothing -- of type `Maybe a` for any `a` +Just "hello" -- `Maybe String` 类型 +Just 1 -- `Maybe Int` 类型 +Nothing -- 对任意 `a` 为 `Maybe a` 类型 ---------------------------------------------------- -- 8. Haskell IO @@ -321,7 +320,7 @@ main' = interact countLines -- 你可以认为一个 `IO ()` 类型的值是表示计算机做的一系列操作,类似命令式语言。 -- 我们可以使用 `do` 声明来把动作连接到一起。 --- 举个列子: +-- 举个列子 sayHello :: IO () sayHello = do putStrLn "What is your name?" @@ -336,7 +335,8 @@ sayHello = do -- 让我们来更进一步理解刚才所使用的函数 `getLine` 是怎样工作的。它的类型是: -- getLine :: IO String --- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序(可能还有其它行为)。 +-- 你可以认为一个 `IO a` 类型的值代表了一个运行时会生成一个 `a` 类型值的程序。 +-- (可能伴随其它行为) -- 我们可以通过 `<-` 保存和重用这个值。 -- 我们也可以实现自己的 `IO String` 类型函数: action :: IO String @@ -348,8 +348,7 @@ action = do -- `return` 不是关键字,只是一个普通函数 return (input1 ++ "\n" ++ input2) -- return :: String -> IO String --- 我们可以像调用 `getLine` 一样调用它: - +-- 我们可以像调用 `getLine` 一样调用它 main'' = do putStrLn "I will echo two lines!" result <- action @@ -358,29 +357,25 @@ main'' = do -- `IO` 类型是一个 "Monad" 的例子。 -- Haskell 通过使用 Monad 使得其本身为纯函数式语言。 --- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO` --- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) ,什么样的函数不是 “纯洁的” - +-- 任何与外界交互的函数(即 IO)都在它的类型声明中标记为 `IO`。 +-- 这告诉我们什么样的函数是“纯洁的”(不与外界交互,不修改状态) , +-- 什么样的函数不是 “纯洁的”。 -- 这个功能非常强大,因为纯函数并发非常容易,由此在 Haskell 中做并发非常容易。 - ---------------------------------------------------- -- 9. Haskell REPL ---------------------------------------------------- -- 键入 `ghci` 开始 REPL。 -- 现在你可以键入 Haskell 代码。 --- 任何新值都需要通过 `let` 来创建: - +-- 任何新值都需要通过 `let` 来创建 let foo = 5 --- 你可以查看任何值的类型,通过命令 `:t`: - +-- 你可以通过命令 `:t` 查看任何值的类型 >:t foo foo :: Integer -- 你也可以运行任何 `IO ()`类型的动作 - > sayHello What is your name? Friend! -- cgit v1.2.3 From cb69cff1be0b22942a29a076d7cabec3fbb5467f Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 11 Apr 2015 12:31:11 +0800 Subject: [c++/cn] Complete the whole translation. --- zh-cn/c++-cn.html.markdown | 410 ++++++++++++++++++++++----------------------- 1 file changed, 205 insertions(+), 205 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 24d2a1b8..cbf89c38 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -9,66 +9,66 @@ translators: lang: zh-cn --- -C++是一種系統編程語言。用它的發明者, -[Bjarne Stroustrup的話](http://channel9.msdn.com/Events/Lang-NEXT/Lang-NEXT-2014/Keynote)來說,C++的設計目標是: +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++中,你的程序會從main()開始執行, -// 該函數的返回值應當爲int型,這個返回值會作爲程序的退出狀態值。 -// 不過,大多數的編譯器(gcc,clang等)也接受 void main() 的函數原型。 -// (參見 http://en.wikipedia.org/wiki/Exit_status 來獲取更多信息) +// 和C语言一样,在C++中,你的程序会从main()开始执行, +// 该函数的返回值应当为int型,这个返回值会作为程序的退出状态值。 +// 不过,大多数的编译器(gcc,clang等)也接受 void main() 的函数原型。 +// (参见 http://en.wikipedia.org/wiki/Exit_status 来获取更多信息) int main(int argc, char** argv) { - // 和C語言一樣,命令行參數通過argc和argv傳遞。 - // argc代表命令行參數的數量, - // 而argv是一個包含「C語言風格字符串」(char *)的數組, - // 其中每個字符串代表一個命令行參數的內容, - // 首個命令行參數是調用該程序時所使用的名稱。 - // 如果你不關心命令行參數的值,argc和argv可以被忽略。 - // 此時,你可以用int main()作爲函數原型。 - - // 退出狀態值爲0時,表示程序執行成功 + // 和C语言一样,命令行参数通过argc和argv传递。 + // argc代表命令行参数的数量, + // 而argv是一个包含“C语言风格字符串”(char *)的数组, + // 其中每个字符串代表一个命令行参数的内容, + // 首个命令行参数是调用该程序时所使用的名称。 + // 如果你不关心命令行参数的值,argc和argv可以被忽略。 + // 此时,你可以用int main()作为函数原型。 + + // 退出状态值为0时,表示程序执行成功 return 0; } -// 然而,C++和C語言也有一些區別: +// 然而,C++和C语言也有一些区别: -// 在C++中,字符字面量的大小是一個字節。 +// 在C++中,字符字面量的大小是一个字节。 sizeof('c') == 1 -// 在C語言中,字符字面量的大小與int相同。 +// 在C语言中,字符字面量的大小与int相同。 sizeof('c') == sizeof(10) -// C++的函數原型與函數定義是嚴格匹配的 -void func(); // 這個函數不能接受任何參數 +// C++的函数原型与函数定义是严格匹配的 +void func(); // 这个函数不能接受任何参数 -// 而在C語言中 -void func(); // 這個函數能接受任意數量的參數 +// 而在C语言中 +void func(); // 这个函数能接受任意数量的参数 -// 在C++中,用nullptr代替C語言中的NULL +// 在C++中,用nullptr代替C语言中的NULL int* ip = nullptr; -// C++也可以使用C語言的標準頭文件, -// 但是需要加上前綴「c」並去掉末尾的「.h」。 +// C++也可以使用C语言的标准头文件, +// 但是需要加上前缀“c”并去掉末尾的“.h”。 #include int main() @@ -78,10 +78,10 @@ int main() } /////////// -// 函數重載 +// 函数重载 /////////// -// C++支持函數重載,【provided each function takes different parameters.】 +// C++支持函数重载,你可以定义一组名称相同而参数不同的函数。 void print(char const* myString) { @@ -95,20 +95,20 @@ void print(int myInt) int main() { - print("Hello"); // 解析爲 void print(const char*) - print(15); // 解析爲 void print(int) + print("Hello"); // 解析为 void print(const char*) + print(15); // 解析为 void print(int) } /////////////////// -// 函數參數的默認值 +// 函数参数的默认值 /////////////////// -// 你可以爲函數的參數指定默認值, -// 它們將會在調用者沒有提供相應參數時被使用。 +// 你可以为函数的参数指定默认值, +// 它们将会在调用者没有提供相应参数时被使用。 void doSomethingWithInts(int a = 1, int b = 4) { - // 對兩個參數進行一些操作 + // 对两个参数进行一些操作 } int main() @@ -118,19 +118,19 @@ int main() 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 Nested { @@ -138,8 +138,8 @@ namespace First { { printf("This is First::Nested::foo\n"); } - } // 結束嵌套的命名空間Nested -} // 結束命名空間First + } // 结束嵌套的命名空间Nested +} // 结束命名空间First namespace Second { void foo() @@ -155,38 +155,38 @@ void foo() int main() { - // 如果沒有特別指定,就從「Second」中取得所需的內容。 + // 如果没有特别指定,就从“Second”中取得所需的内容。 using namespace Second; - foo(); // 顯示「This is Second::foo」 - First::Nested::foo(); // 顯示「This is First::Nested::foo」 - ::foo(); // 顯示「This is global foo」 + foo(); // 显示“This is Second::foo” + First::Nested::foo(); // 显示“This is First::Nested::foo” + ::foo(); // 显示“This is global foo” } //////////// -// 輸入/輸出 +// 输入/输出 //////////// -// C++使用「流」來輸入輸出。<<是流的插入運算符,>>是流提取運算符。 -// cin、cout、和cerr分別代表 -// stdin(標準輸入)、stdout(標準輸出)和stderr(標準錯誤)。 +// C++使用“流”来输入输出。<<是流的插入运算符,>>是流提取运算符。 +// cin、cout、和cerr分别代表 +// stdin(标准输入)、stdout(标准输出)和stderr(标准错误)。 -#include // 引入包含輸入/輸出流的頭文件 +#include // 引入包含输入/输出流的头文件 -using namespace std; // 輸入輸出流在std命名空間(也就是標準庫)中。 +using namespace std; // 输入输出流在std命名空间(也就是标准库)中。 int main() { int myInt; - // 在標準輸出(終端/顯示器)中顯示 + // 在标准输出(终端/显示器)中显示 cout << "Enter your favorite number:\n"; - // 從標準輸入(鍵盤)獲得一個值 + // 从标准输入(键盘)获得一个值 cin >> myInt; // cout也提供了格式化功能 cout << "Your favorite number is " << myInt << "\n"; - // 顯示「Your favorite number is 」 + // 显示“Your favorite number is ” cerr << "Used for error messages"; } @@ -195,20 +195,20 @@ int main() // 字符串 ///////// -// C++中的字符串是對象,它們有很多成員函數 +// C++中的字符串是对象,它们有很多成员函数 #include -using namespace std; // 字符串也在std命名空間(標準庫)中。 +using namespace std; // 字符串也在std命名空间(标准库)中。 string myString = "Hello"; string myOtherString = " World"; -// + 可以用於連接字符串。 +// + 可以用于连接字符串。 cout << myString + myOtherString; // "Hello World" cout << myString + " You"; // "Hello You" -// C++中的字符串是可變的,具有「值語義」。 +// C++中的字符串是可变的,具有“值语义”。 myString.append(" Dog"); cout << myString; // "Hello Dog" @@ -217,11 +217,11 @@ cout << myString; // "Hello Dog" // 引用 ///////////// -// 除了支持C語言中的指針類型以外,C++還提供了_引用_。 -// 引用是一種特殊的指針類型,一旦被定義就不能重新賦值,並且不能被設置爲空值。 -// 使用引用時的語法與原變量相同: -// 也就是說,對引用類型進行解引用時,不需要使用*; -// 賦值時也不需要用&來取地址。 +// 除了支持C语言中的指针类型以外,C++还提供了_引用_。 +// 引用是一种特殊的指针类型,一旦被定义就不能重新赋值,并且不能被设置为空值。 +// 使用引用时的语法与原变量相同: +// 也就是说,对引用类型进行解引用时,不需要使用*; +// 赋值时也不需要用&来取地址。 using namespace std; @@ -229,76 +229,76 @@ string foo = "I am foo"; string bar = "I am bar"; -string& fooRef = foo; // 建立了一個對foo的引用。 -fooRef += ". Hi!"; // 通過引用來修改foo的值 +string& fooRef = foo; // 建立了一个对foo的引用。 +fooRef += ". Hi!"; // 通过引用来修改foo的值 cout << fooRef; // "I am foo. Hi!" -// 這句話的並不會改變fooRef的指向,其效果與「foo = bar」相同。 -// 也就是說,在執行這條語句之後,foo == "I am bar"。 +// 这句话的并不会改变fooRef的指向,其效果与“foo = bar”相同。 +// 也就是说,在执行这条语句之后,foo == "I am bar"。 fooRef = bar; const string& barRef = bar; // 建立指向bar的常量引用。 -// 和C語言中一樣,(指針和引用)聲明爲常量時,對應的值不能被修改。 -barRef += ". Hi!"; // 這是錯誤的,不能修改一個常量引用的值。 +// 和C语言中一样,(指针和引用)声明为常量时,对应的值不能被修改。 +barRef += ". Hi!"; // 这是错误的,不能修改一个常量引用的值。 /////////////////// -// 類與面向對象編程 +// 类与面向对象编程 /////////////////// -// 有關類的第一個示例 +// 有关类的第一个示例 #include -// 聲明一個類。 -// 類通常在頭文件(.h或.hpp)中聲明。 +// 声明一个类。 +// 类通常在头文件(.h或.hpp)中声明。 class Dog { - // 成員變量和成員函數默認情況下是私有(private)的。 + // 成员变量和成员函数默认情况下是私有(private)的。 std::string name; int weight; -// 在這個標籤之後,所有聲明都是公有(public)的, -// 直到重新指定「private:」(私有繼承)或「protected:」(保護繼承)爲止 +// 在这个标签之后,所有声明都是公有(public)的, +// 直到重新指定“private:”(私有继承)或“protected:”(保护继承)为止 public: - // 默認的構造器 + // 默认的构造器 Dog(); - // 這裏是成員函數聲明的一個例子。 - // 可以注意到,我們在此處使用了std::string,而不是using namespace std - // 語句using namespace絕不應當出現在頭文件當中。 + // 这里是成员函数声明的一个例子。 + // 可以注意到,我们在此处使用了std::string,而不是using namespace std + // 语句using namespace绝不应当出现在头文件当中。 void setName(const std::string& dogsName); void setWeight(int dogsWeight); - // 如果一個函數不對對象的狀態進行修改, - // 應當在聲明中加上const。 - // 這樣,你就可以對一個以常量方式引用的對象執行該操作。 - // 同時可以注意到,當父類的成員函數需要被子類重寫時, - // 父類中的函數必須被顯式聲明爲_虛函數(virtual)_。 - // 考慮到性能方面的因素,函數默認情況下不會被聲明爲虛函數。 + // 如果一个函数不对对象的状态进行修改, + // 应当在声明中加上const。 + // 这样,你就可以对一个以常量方式引用的对象执行该操作。 + // 同时可以注意到,当父类的成员函数需要被子类重写时, + // 父类中的函数必须被显式声明为_虚函数(virtual)_。 + // 考虑到性能方面的因素,函数默认情况下不会被声明为虚函数。 virtual void print() const; - // 函數也可以在class body內部定義。 - // 這樣定義的函數會自動成爲內聯函數。 + // 函数也可以在class body内部定义。 + // 这样定义的函数会自动成为内联函数。 void bark() const { std::cout << name << " barks!\n" } - // 除了構造器以外,C++還提供了析構器。 - // 當一個對象被刪除或者脫離其定義域時時,它的析構函數會被調用。 - // 這使得RAII這樣的強大範式(參見下文)成爲可能。 - // 爲了衍生出子類來,基類的析構函數必須定義爲虛函數。 + // 除了构造器以外,C++还提供了析构器。 + // 当一个对象被删除或者脱离其定义域时时,它的析构函数会被调用。 + // 这使得RAII这样的强大范式(参见下文)成为可能。 + // 为了衍生出子类来,基类的析构函数必须定义为虚函数。 virtual ~Dog(); -}; // 在類的定義之後,要加一個分號 +}; // 在类的定义之后,要加一个分号 -}; // 記住,在類的定義之後,要加一個分號! +}; // 记住,在类的定义之后,要加一个分号! -// 類的成員函數通常在.cpp文件中實現。 +// 类的成员函数通常在.cpp文件中实现。 void Dog::Dog() { std::cout << "A dog has been constructed\n"; } -// 對象(例如字符串)應當以引用的形式傳遞, -// 對於不需要修改的對象,最好使用常量引用。 +// 对象(例如字符串)应当以引用的形式传递, +// 对于不需要修改的对象,最好使用常量引用。 void Dog::setName(const std::string& dogsName) { name = dogsName; @@ -309,7 +309,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時出現 +// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时出现 void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -325,7 +325,7 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 虛函數的virtual關鍵字只需要在聲明時使用,不需要在定義時重複 +// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复 void Dog::print() const { std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; @@ -337,32 +337,32 @@ void Dog::~Dog() } int main() { - Dog myDog; // 此時顯示「A dog has been constructed」 + Dog myDog; // 此时显示“A dog has been constructed” myDog.setName("Barkley"); myDog.setWeight(10); - myDog.printDog(); // 顯示「Dog is Barkley and weighs 10 kg」 + myDog.printDog(); // 显示“Dog is Barkley and weighs 10 kg” return 0; -} // 顯示「Goodbye Barkley」 +} // 显示“Goodbye Barkley” -// 繼承: +// 继承: -// 這個類繼承了Dog類中的公有(public)和保護(protected)對象 +// 这个类继承了Dog类中的公有(public)和保护(protected)对象 class OwnedDog : public Dog { void setOwner(const std::string& dogsOwner) - // 重寫OwnedDogs類的print方法。 - // 如果你不熟悉子類多態的話,可以參考這個頁面中的概述: + // 重写OwnedDogs类的print方法。 + // 如果你不熟悉子类多态的话,可以参考这个页面中的概述: // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping - // override關鍵字是可選的,它確保你是在重寫基類中的方法。 + // override关键字是可选的,它确保你所重写的是基类中的方法。 void print() const override; private: std::string owner; }; -// 與此同時,在對應的.cpp文件裏: +// 与此同时,在对应的.cpp文件里: void OwnedDog::setOwner(const std::string& dogsOwner) { @@ -371,7 +371,7 @@ void OwnedDog::setOwner(const std::string& dogsOwner) void OwnedDog::print() const { - Dog::print(); // 調用基類Dog中的print方法 + Dog::print(); // 调用基类Dog中的print方法 // "Dog is and weights " std::cout << "Dog is owned by " << owner << "\n"; @@ -379,45 +379,46 @@ void OwnedDog::print() const } ///////////////////// -// 初始化與運算符重載 +// 初始化与运算符重载 ///////////////////// -// 在C++中,你可以重載+、-、*、/等運算符的行爲。 -// 【This is done by defining a function -// which is called whenever the operator is used. +// 在C++中,通过定义一些特殊名称的函数, +// 你可以重载+、-、*、/等运算符的行为。 +// 当运算符被使用时,这些特殊函数会被调用,从而实现运算符重载。 #include using namespace std; class Point { public: - // 可以以這樣的方式爲成員變量設置默認值。 + // 可以以这样的方式为成员变量设置默认值。 double x = 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() { }; - // 【The following syntax is known as an initialization list - // and is the proper way to initialize class member values + // 下面使用的语法称为初始化列表, + // 这是初始化类中成员变量的正确方式。 Point (double a, double b) : x(a), y(b) - { /* 【Do nothing except initialize the values */ } + { /* 除了初始化成员变量外,什么都不做 */ } - // 重載 + 運算符 + // 重载 + 运算符 Point operator+(const Point& rhs) const; - // 重載 += 運算符 + // 重载 += 运算符 Point& operator+=(const Point& rhs); - // 增加 - 和 -= 運算符也是有意義的,這裏不再贅述。 + // 增加 - 和 -= 运算符也是有意义的,但这里不再赘述。 }; 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); } @@ -431,88 +432,88 @@ Point& Point::operator+=(const Point& rhs) int main () { Point up (0,1); Point right (1,0); - // 這裏調用了Point類型的運算符「+」 - // 調用up(Point類型)的「+」方法,並以right作爲函數的參數 + // 这里使用了Point类型的运算符“+” + // 调用up(Point类型)的“+”方法,并以right作为函数的参数 Point result = up + right; - // 顯示「Result is upright (1,1)」 + // 显示“Result is upright (1,1)” cout << "Result is upright (" << result.x << ',' << result.y << ")\n"; return 0; } /////////// -// 異常處理 +// 异常处理 /////////// -// 標準庫中提供了一些基本的異常類型 -// (參見http://en.cppreference.com/w/cpp/error/exception) -// 但是,其他任何類型也可以作爲一個異常被拋出 +// 标准库中提供了一些基本的异常类型 +// (参见http://en.cppreference.com/w/cpp/error/exception) +// 但是,其他任何类型也可以作为一个异常被拋出 #include -// 在_try_代碼塊中拋出的異常可以被隨後的_catch_捕獲。 +// 在_try_代码块中拋出的异常可以被随后的_catch_捕获。 try { - // 不要用 _new_關鍵字在堆上爲異常分配空間。 + // 不要用 _new_关键字在堆上为异常分配空间。 throw std::exception("A problem occurred"); } -// 如果拋出的異常是一個對象,可以用常量引用來捕獲它 +// 如果拋出的异常是一个对象,可以用常量引用来捕获它 catch (const std::exception& ex) { std::cout << ex.what(); -// 捕獲尚未被_catch_處理的所有錯誤 +// 捕获尚未被_catch_处理的所有错误 } catch (...) { std::cout << "Unknown exception caught"; - throw; // 重新拋出異常 + throw; // 重新拋出异常 } /////// // RAII /////// -// RAII指的是「资源获取就是初始化」(Resource Allocation Is Initialization), -// 它被視作C++中最強大的編程範式之一。 -// 簡單說來,它指的是,用構造函數來獲取一個對象的資源, -// 相應的,借助析構函數來釋放對象的資源。 +// RAII指的是“资源获取就是初始化”(Resource Allocation Is Initialization), +// 它被视作C++中最强大的编程范式之一。 +// 简单说来,它指的是,用构造函数来获取一个对象的资源, +// 相应的,借助析构函数来释放对象的资源。 -// 爲了理解這一範式的用處,讓我們考慮某個函數使用文件句柄時的情況: +// 为了理解这一范式的用处,让我们考虑某个函数使用文件句柄时的情况: void doSomethingWithAFile(const char* filename) { - // 首先,讓我們假設一切都會順利進行。 + // 首先,让我们假设一切都会顺利进行。 - FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); - fclose(fh); // 關閉文件句柄 + fclose(fh); // 关闭文件句柄 } -// 不幸的是,隨着錯誤處理機制的引入,事情會變得複雜。 -// 假設fopen函數有可能執行失敗, -// 而doSomethingWithTheFile和doSomethingElseWithIt會在失敗時返回錯誤代碼。 -// (雖然異常是C++中處理錯誤的推薦方式, -// 但是某些程序員,尤其是有C語言背景的,並不認可異常捕獲機制的作用)。 -// 現在,我們必須檢查每個函數調用是否成功執行,並在問題發生的時候關閉文件句柄。 +// 不幸的是,随着错误处理机制的引入,事情会变得复杂。 +// 假设fopen函数有可能执行失败, +// 而doSomethingWithTheFile和doSomethingElseWithIt会在失败时返回错误代码。 +// (虽然异常是C++中处理错误的推荐方式, +// 但是某些程序员,尤其是有C语言背景的,并不认可异常捕获机制的作用)。 +// 现在,我们必须检查每个函数调用是否成功执行,并在问题发生的时候关闭文件句柄。 bool doSomethingWithAFile(const char* filename) { - FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 - if (fh == nullptr) // 當執行失敗是,返回的指針是nullptr - return false; // 向調用者彙報錯誤 + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 + if (fh == nullptr) // 当执行失败是,返回的指针是nullptr + return false; // 向调用者汇报错误 - // 假設每個函數會在執行失敗時返回false + // 假设每个函数会在执行失败时返回false if (!doSomethingWithTheFile(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // 反饋錯誤 + fclose(fh); // 关闭文件句柄,避免造成内存泄漏。 + return false; // 反馈错误 } if (!doSomethingElseWithIt(fh)) { - fclose(fh); // Close the file handle so it doesn't leak. - return false; // 反饋錯誤 + fclose(fh); // 关闭文件句柄 + return false; // 反馈错误 } - fclose(fh); // Close the file handle so it doesn't leak. - return true; // 指示函數已成功執行 + fclose(fh); // 关闭文件句柄 + return true; // 指示函数已成功执行 } -// C語言的程序員通常會借助goto語句簡化上面的代碼: +// C语言的程序员通常会借助goto语句简化上面的代码: bool doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); @@ -525,19 +526,19 @@ bool doSomethingWithAFile(const char* filename) if (!doSomethingElseWithIt(fh)) goto failure; - fclose(fh); // 關閉文件 - return true; // 執行成功 + fclose(fh); // 关闭文件 + return true; // 执行成功 failure: fclose(fh); - return false; // 反饋錯誤 + return false; // 反馈错误 } -// 如果用異常捕獲機制來指示錯誤的話, -// 代碼會變得清晰一些,但是仍然有優化的餘地。 +// 如果用异常捕获机制来指示错误的话, +// 代码会变得清晰一些,但是仍然有优化的餘地。 void doSomethingWithAFile(const char* filename) { - FILE* fh = fopen(filename, "r"); // 以只讀模式打開文件 + FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 if (fh == nullptr) throw std::exception("Could not open the file."); @@ -546,45 +547,44 @@ void doSomethingWithAFile(const char* filename) doSomethingElseWithIt(fh); } catch (...) { - fclose(fh); // 保證出錯的時候文件被正確關閉 + fclose(fh); // 保证出错的时候文件被正确关闭 throw; // Then re-throw the exception. } - fclose(fh); // 關閉文件 - // 所有工作順利完成 + fclose(fh); // 关闭文件 + // 所有工作顺利完成 } -// 【Compare this to the use of C++'s file stream class (fstream) -// fstream利用自己的析構器來關閉文件句柄。 -// 【Recall from above that destructors are automatically called -// whenver an object falls out of scope. +// 相比之下,使用C++中的文件流类(fstream)时, +// fstream会利用自己的析构器来关闭文件句柄。 +// 只要离开了某一对象的定义域,它的析构函数就会被自动调用。 void doSomethingWithAFile(const std::string& filename) { - // ifstream是輸入文件流(input file stream)的簡稱 - std::ifstream fh(filename); // Open the file + // ifstream是输入文件流(input file stream)的简称 + std::ifstream fh(filename); // 打开一个文件 - // 對文件進行一些操作 + // 对文件进行一些操作 doSomethingWithTheFile(fh); doSomethingElseWithIt(fh); -} // 文件已經被析構器自動關閉 - -// 與上面幾種方式相比,這種方式有着_明顯_的優勢: -// 1. 無論發生了什麼情況,資源(此例當中是文件句柄)都會被正確關閉。 -// 只要你正確使用了析構器,就_不會_因爲忘記關閉句柄,造成資源的泄漏。 -// 2. 可以注意到,通過這種方式寫出來的代碼十分簡潔。 -// 析構器會在後臺關閉文件句柄,不再需要你來操心這些瑣事。 -// 3. 【The code is exception safe. -// 無論在函數中的何處拋出異常,都不會阻礙對文件資源的釋放。 - -// 地道的C++代碼應當把RAII的使用擴展到各種類型的資源上,包括: -// - 用unique_ptr和shared_ptr管理的內存 -// - 各種數據容器,例如標準庫中的鏈表、向量(容量自動擴展的數組)、散列表等; -// 當它們脫離作用域時,析構器會自動釋放其中儲存的內容。 -// - 用lock_guard和unique_lock實現的互斥 +} // 文件已经被析构器自动关闭 + +// 与上面几种方式相比,这种方式有着_明显_的优势: +// 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。 +// 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。 +// 2. 可以注意到,通过这种方式写出来的代码十分简洁。 +// 析构器会在后臺关闭文件句柄,不再需要你来操心这些琐事。 +// 3. 这种方式的代码具有异常安全性。 +// 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。 + +// 地道的C++代码应当把RAII的使用扩展到各种类型的资源上,包括: +// - 用unique_ptr和shared_ptr管理的内存 +// - 各种数据容器,例如标准库中的链表、向量(容量自动扩展的数组)、散列表等; +// 当它们脱离作用域时,析构器会自动释放其中储存的内容。 +// - 用lock_guard和unique_lock实现的互斥 ``` -擴展閱讀: +扩展阅读: - 提供了最新的語法參考。 + 提供了最新的语法参考。 -可以在 找到一些補充資料。 +可以在 找到一些补充资料。 -- cgit v1.2.3 From c38d8d93135561e8c0afbe20a5b16b39917ee06c Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Sat, 11 Apr 2015 12:40:47 +0800 Subject: [c++/cn] Update the translated file name. --- zh-cn/c++-cn.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index cbf89c38..eed20721 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -1,6 +1,6 @@ --- language: c++ -filename: learncpp.cpp +filename: learncpp-cn.cpp contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Matt Kline", "https://github.com/mrkline"] -- cgit v1.2.3 From b95c6b0dae6b91d1c88c337863e8fe182e326b4e Mon Sep 17 00:00:00 2001 From: yejinchang Date: Wed, 15 Apr 2015 15:54:53 +0800 Subject: translate scala doc into chinese --- zh-cn/scala-cn.html.markdown | 553 +++++++++++++++++++++++++++++-------------- 1 file changed, 378 insertions(+), 175 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 58f5cd47..5d5d93c7 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -4,8 +4,10 @@ filename: learnscala-zh.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] translators: - ["Peiyong Lin", ""] + - ["Jinchang Ye", "http://github.com/alwayswithme"] lang: zh-cn --- @@ -17,23 +19,31 @@ Scala - 一门可拓展性的语言 自行设置: 1) 下载 Scala - http://www.scala-lang.org/downloads - 2) unzip/untar 到你喜欢的地方,放在路径中的 bin 目录下 - 3) 在终端输入 scala,开启 Scala 的 REPL,你会看到提示符: + 2) unzip/untar 到您喜欢的地方,并把 bin 子目录添加到 path 环境变量 + 3) 在终端输入 scala,启动 Scala 的 REPL,您会看到提示符: scala> - 这就是所谓的 REPL,你现在可以在其中运行命令,让我们做到这一点: + 这就是所谓的 REPL (读取-求值-输出循环,英语: Read-Eval-Print Loop), + 您可以在其中输入合法的表达式,结果会被打印。 + 在教程中我们会进一步解释 Scala 文件是怎样的,但现在先了解一点基础。 */ -println(10) // 打印整数 10 -println("Boo!") // 打印字符串 "BOO!" +///////////////////////////////////////////////// +// 1. 基础 +///////////////////////////////////////////////// +// 单行注释开始于两个斜杠 -// 一些基础 +/* + 多行注释,如您之前所见,看起来像这样 +*/ // 打印并强制换行 println("Hello world!") +println(10) + // 没有强制换行的打印 print("Hello world") @@ -41,13 +51,19 @@ print("Hello world") // val 声明是不可变的,var 声明是可修改的。不可变性是好事。 val x = 10 // x 现在是 10 x = 20 // 错误: 对 val 声明的变量重新赋值 -var x = 10 -x = 20 // x 现在是 20 +var y = 10 +y = 20 // y 现在是 20 -// 单行注释开始于两个斜杠 -/* -多行注释看起来像这样。 +/* + Scala 是静态语言,但注意上面的声明方式,我们没有指定类型。 + 这是因为类型推导的语言特性。大多数情况, Scala 编译器可以推测变量的类型, + 所以您不需要每次都输入。可以像这样明确声明变量类型: */ +val z: Int = 10 +val a: Double = 1.0 + +// 注意从 Int 到 Double 的自动转型,结果是 10.0, 不是 10 +val b: Double = 10 // 布尔值 true @@ -64,9 +80,11 @@ true == false // false 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 -// 在 REPL 计算一个命令会返回给你结果的类型和值 +// 在 REPL 计算一个表达式会返回给您结果的类型和值 1 + 7 @@ -77,58 +95,190 @@ true == false // false 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 - 1+7 的结果是一样的 + 注意 "res29" 是一个连续生成的变量名,用以存储您输入的表达式结果, + 您看到的输入可能不一样。 */ +"Scala strings are surrounded by double quotes" +'a' // Scala 的字符 +// '不存在单引号字符串' <= 这会导致错误 -// 包括函数在内,每一个事物都是对象。在 REPL 中输入: +// 字符串定义了常见的 Java 方法 +"hello world".length +"hello world".substring(2, 6) +"hello world".replace("C", "3") -7 // 结果 res30: Int = 7 (res30 是一个生成的结果的 var 命名) +// 也有一些额外的 Scala 方法,另请参见:scala.collection.immutable.StringOps +"hello world".take(5) +"hello world".drop(5) -// 下一行给你一个接收一个 Int 类型并返回该数的平方的函数 -(x:Int) => x * x +// 字符串改写:留意前缀 "s" +val n = 45 +s"We have $n apples" // => "We have 45 apples" -// 你可以分配给函数一个标识符,像这样: -val sq = (x:Int) => x * x +// 在要改写的字符串中使用表达式也是可以的 +val a = Array(11, 9, 6) +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -/* 上面的例子说明 - - sq: Int => Int = +// 添加 "f" 前缀对要改写的字符串进行格式化 +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" - 意味着这次我们给予了 sq 这样一个显式的名字给一个接受一个 Int 类型值并返回 一个 Int 类型值的函数 +// 未处理的字符串,忽略特殊字符。 +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." - sq 可以像下面那样被执行: -*/ +// 一些字符需要转义,比如字符串中的双引号 +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -sq(10) // 返回给你:res33: Int = 100. +// 三个双引号可以使字符串跨越多行,并包含引号 +val html = """
+

Press belo', Joe

+ +
""" -// Scala 允许方法和函数返回或者接受其它的函数或者方法作为参数。 -val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数 -List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 +///////////////////////////////////////////////// +// 2. 函数 +///////////////////////////////////////////////// + +// 函数可以这样定义: +// +// def functionName(args...): ReturnType = { body... } +// +// 如果您以前学习过传统的编程语言,注意 return 关键字的省略。 +// 在 Scala 中, 函数代码块最后一条表达式就是返回值。 +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} -// 匿名函数可以被使用来代替有命名的函数: -List(1, 2, 3) map (x => x + 10) +// 如果函数体是单行表达式,{ } 可以省略: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 -List(1, 2, 3) map (_ + 10) +// 函数调用的语法是熟知的: +sumOfSquares(3, 4) // => 25 -// 如果你所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 -List("Dom", "Bob", "Natalia") foreach println +// 在多数情况下 (递归函数是需要注意的例外), 函数返回值可以省略, +// 变量所用的类型推导一样会应用到函数返回值中: +def sq(x: Int) = x * x // 编译器会推断得知返回值是 Int + +// 函数可以有默认参数 +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 + + +// 匿名函数是这样的: +(x:Int) => x * x + +// 和 def 不同,如果语义清晰,匿名函数的输入类型也可以省略。 +// 类型 "Int => Int" 意味着这个函数接收一个 Int 并返回一个 Int。 +val sq: Int => Int = x => x * x + +// 匿名函数的调用也是类似的: +sq(10) // => 100 + +// 如果您的匿名函数有一到两个参数,每一个参数仅使用一次, +// Scala 提供一个更简洁的方式来定义他们。这样的匿名函数极为常见, +// 在数据结构部分会明显可见。 +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + + +// return 关键字是存在的,但它从最里面包裹了 return 的 def 函数中返回。 +// 警告: 在 Scala 中使用 return 容易出错,应该避免使用。 +// 在匿名函数中没有效果,例如: +def foo(x: Int): Int = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // 这一行令 z 成为 foo 函数的返回值! + else + z + 2 // 这一行是 anonFunc 函数的返回值 + } + anonFunc(x) // 这一行是 foo 函数的返回值 +} + +/* + * 译者注:此处是指匿名函数中的 return z 成为最后执行的语句, + * 在 anonFunc(x) 下面的表达式(假设存在)不再执行。如果 anonFunc + * 是用 def 定义的函数, return z 仅返回到 anonFunc(x) , + * 在 anonFunc(x) 下面的表达式(假设存在)会继续执行。 + */ +///////////////////////////////////////////////// +// 3. 控制语句 +///////////////////////////////////////////////// -// 数据结构 +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// 留意: Scala 对点和括号的要求比较宽松,对这些规则加以区分。 +// 这有助于写出读起来像英语的 DSL(领域特定语言) 和 API(应用编程接口)。 + +(5 to 1 by -1) foreach ( println ) + +// while 循环 +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // 没错,再执行一次,发生了什么?为什么? + +i // 显示 i 的值。注意 while 是经典的循环方式,它连续执行并改变循环中的变量。 + // while 执行很快,比 Java 的循环快,但像上面所看到的那样用组合子和推导式 + // 更易于理解和并行化。 + +// do while 循环 +do { + println("x is still less than 10"); + x += 1 +} while (x < 10) + +// Scala 中尾递归是一种符合语言习惯的递归方式。 +// 递归函数需要清晰的返回类型,编译器不能推断得知。 +// 这是一个 Unit。 +def showNumbersInRange(a:Int, b:Int):Unit = { + print(a) + if (a < b) + showNumbersInRange(a + 1, b) +} +showNumbersInRange(1,14) + + +// 条件语句 + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nay") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + + +///////////////////////////////////////////////// +// 4. 数据结构 +///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) a(0) a(3) -a(21) // 这会抛出一个异常 +a(21) // 抛出异常 val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") -m("bottle") // 这会抛出一个异常 +m("bottle") // 抛出异常 val safeM = m.withDefaultValue("no lo se") safeM("bottle") @@ -137,9 +287,9 @@ val s = Set(1, 3, 7) s(0) s(1) -/* 查看 map 的文档 - * 点击[这里](http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map) - * 确保你可以读它 +/* 这里查看 map 的文档 - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * 并确保你会阅读 */ @@ -157,7 +307,7 @@ s(1) val divideInts = (x:Int, y:Int) => (x / y, x % y) -divideInts(10,3) // 函数 divideInts 返回你结果和余数 +divideInts(10,3) // 函数 divideInts 返回您结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 @@ -168,234 +318,287 @@ d._1 d._2 +///////////////////////////////////////////////// +// 5. 面向对象编程 +///////////////////////////////////////////////// -// 选择器 - -s.map(sq) - -val sSquared = s. map(sq) - -sSquared.filter(_ < 10) +/* + 旁白: 教程中到现在为止我们所做的一切只是简单的表达式(值,函数等)。 + 这些表达示可以输入到命令行解释器中作为快速测试,但它们无法单一的存在于 Scala + 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。而 Scala 允许存 + 在的顶级结构是: -sSquared.reduce (_+_) + - objects + - classes + - case classes + - traits -// filter 函数接受一个预测(一个函数,形式为 A -> Boolean) 并选择出所有的元素满足这个预测 + 现在来解释这些是什么。 +*/ -List(1, 2, 3) filter (_ > 2) // List(3) -List( - Person(name = "Dom", age = 23), - Person(name = "Bob", age = 30) -).filter(_.age > 25) // List(Person("Bob", 30)) +// 类和其他语言的类相似,构造器参数在类名后声明,初始化在类结构体中完成。 +class Dog(br: String) { + // 构造器代码在此 + var breed: String = br + // 定义名为 bark 的方法,返回字符串 + def bark = "Woof, woof!" -// Scala 的 foreach 方法定义在特定的接受一个类型的集合上 -// 返回 Unit(一个 void 方法) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println + // 值和方法作用域假定为 public。"protected" 和 "private" 关键字也是可用的。 + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类需要被声明为 abstract + // abstract class Dog(...) { ... } + // def chaseAfter(what: String): String +} +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" -// For 包含 +// "object" 关键字创造一种类型和该类型的单例。 +// Scala 的 class 常常也含有一个 “伴生对象”,class 中包含每个实例的行为,所有实例 +// 共用的行为则放入 object 中。两者的区别和其他语言中方法和静态方法类似。 +// 请注意 object 和 class 可以同名。 +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} -for { n <- s } yield sq(n) -val nSquared2 = for { n <- s } yield sq(n) +// Case 类是有额外内建功能的类。Scala 初学者常遇到的问题之一便是何时用类 +// 和何时用 case 类。界线比较模糊,但通常类倾向于封装,多态和行为。类中的值 +// 的作用域一般为 private , 只有方向是暴露的。case 类的主要目的是放置不可变 +// 数据。它们通常只有几个方法,且方法几乎没有副作用。 +case class Person(name: String, phoneNumber: String) -for { n <- nSquared2 if n < 10 } yield n +// 创造新实例,注意 case 类不需要 "new" 关键字 +val george = Person("George", "1234") +val kate = Person("Kate", "4567") -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +// 使用 case 类,您可以轻松得到一些功能,像 getters: +george.phoneNumber // => "1234" -/* 注意:这些不是 for 循环. 一个 for 循环的语义是 '重复'('repeat'), - 然而,一个 for-包含 定义了一个两个数据结合间的关系 */ +// 每个字段的相等性(无需覆盖 .equals) +Person("George", "1234") == Person("Kate", "1236") // => false +// 简单的拷贝方式 +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") +// 还有很多。case 类同时可以用于模式匹配,接下来会看到。 -// 循环和迭代 -1 to 5 -val r = 1 to 5 -r.foreach( println ) +// 敬请期待 Traits ! -r foreach println -// 注意:Scala 是相当宽容的当它遇到点和括号 - 分别地学习这些规则。 -// 这帮助你编写读起来像英语的 DSLs 和 APIs -(5 to 1 by -1) foreach ( println ) +///////////////////////////////////////////////// +// 6. 模式匹配 +///////////////////////////////////////////////// -// while 循环 -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - -while (i < 10) { println("i " + i); i+=1 } // 发生了什么?为什么? - -i // 展示 i 的值。注意到 while 是一个传统意义上的循环 - // 它顺序地执行并且改变循环变量的值。while 非常快,比 Java // 循环快, - // 但是在其上使用选择器和包含更容易理解和并行。 - -// do while 循环 -do { - println("x is still less then 10"); - x += 1 -} while (x < 10) +// 模式匹配是一个强大和常用的 Scala 特性。这是用模式匹配一个 case 类的例子。 +// 留意:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 +// fall-through 现象不会发生。 -// 在 Scala中,尾递归是一种惯用的执行循环的方式。 -// 递归函数需要显示的返回类型,编译器不能推断出类型。 -// 这里它是 Unit。 -def showNumbersInRange(a:Int, b:Int):Unit = { - print(a) - if (a < b) - showNumbersInRange(a + 1, b) +def matchPerson(person: Person): String = person match { + // Then you specify the patterns: + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number } +val email = "(.*)@(.*)".r // 定义下一个例子会用到的正则 +// 模式匹配看起来和 C语言家族的 switch 语句相似,但更为强大。 +// Scala 中您可以很多东西: +def matchEverything(obj: Any): String = obj match { + // 匹配值: + case "Hello world" => "Got the string Hello world" -// 条件语句 - -val x = 10 - -if (x == 1) println("yeah") -if (x == 10) println("yeah") -if (x == 11) println("yeah") -if (x == 11) println ("yeah") else println("nay") + // 匹配类型: + case x: Double => "Got a Double: " + x -println(if (x == 10) "yeah" else "nope") -val text = if (x == 10) "yeah" else "nope" + // 匹配时指定条件 + case x: Int if x > 10000 => "Got a pretty big number!" -var i = 0 -while (i < 10) { println("i " + i); i+=1 } + // 像之前一样匹配 case 类: + case Person(name, number) => s"Got contact info for $name!" + // 匹配正则表达式: + case email(name, domain) => s"Got email address $name@$domain" + // 匹配元组: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// 面向对象特性 + // 匹配数据结构: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -// 类名是 Dog -class Dog { - //bark 方法,返回字符串 - def bark: String = { - // the body of the method - "Woof, woof!" - } + // 模式可以嵌套 + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" } -// 类可以包含几乎其它的构造,包括其它的类, -// 函数,方法,对象,case 类,特性等等。 - - +// 事实上,你可以对任何有 "unapply" 方法的对象进行模式匹配。 +// 这个特性如此强大以致于 Scala 允许定义一个函数作为模式匹配: +val patternFunc: Person => String = { + case Person("George", number) => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} -// Case 类 -case class Person(name:String, phoneNumber:String) +///////////////////////////////////////////////// +// 7. 函数式编程 +///////////////////////////////////////////////// -Person("George", "1234") == Person("Kate", "1236") +// Scala 允许方法和函数作为其他方法和函数的参数和返回值。 +val add10: Int => Int = _ + 10 // 一个接受一个 Int 类型参数并返回一个 Int 类型值的函数 +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 +// 匿名函数可以被使用来代替有命名的函数: +List(1, 2, 3) map (x => x + 10) +// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 +List(1, 2, 3) map (_ + 10) -// 模式匹配 +// 如果您所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 +List("Dom", "Bob", "Natalia") foreach println -val me = Person("George", "1234") -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} +// 组合子 -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } +// 译注: val sq: Int => Int = x => x * x +s.map(sq) -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val sSquared = s. map(sq) -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +sSquared.filter(_ < 10) -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } +sSquared.reduce (_+_) -val kate = Person("Kate", "1234") +// filter 函数接受一个 predicate (函数从 A -> Boolean)并选择 +// 所有满足 predicate 的元素 +List(1, 2, 3) filter (_ > 2) // List(3) +case class Person(name:String, age:Int) +List( + Person(name = "Dom", age = 23), + Person(name = "Bob", age = 30) +).filter(_.age > 25) // List(Person("Bob", 30)) -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } +// Scala 的 foreach 方法定义在特定集合中,接受一个类型并返回 Unit (void 方法) +val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println +// For 推导式 -// 正则表达式 +for { n <- s } yield sq(n) -val email = "(.*)@(.*)".r // 在字符串上调用 r 会使它变成一个正则表达式 +val nSquared2 = for { n <- s } yield sq(n) -val email(user, domain) = "henry@zkpr.com" +for { n <- nSquared2 if n < 10 } yield n -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name -} +for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +/* 注意,这些不是 for 循环,for 循环的语义是‘重复’,然而 for 推导式定义 + 两个数据集合的关系。 */ -// 字符串 +///////////////////////////////////////////////// +// 8. 隐式转换 +///////////////////////////////////////////////// -"Scala 字符串被双引号包围" // -'a' // Scala 字符 -'单引号的字符串不存在' // 错误 -"字符串拥有通常的 Java 方法定义在其上".length -"字符串也有额外的 Scala 方法".reverse +/* 警告 警告: 隐式转换是 Scala 中一套强大的特性,因此容易被滥用。 + * Scala 初学者在理解它们的工作原理和最佳实践之前,应抵制使用它的诱惑。 + * 我们加入这一章节仅因为它们在 Scala 的库中太过常见,导致没有用隐式转换的库 + * 就不可能做有意义的事情。这章节主要让你理解和使用隐式转换,而不是自己声明。 + */ -// 参见: scala.collection.immutable.StringOps +// 任何值(val, 函数,对象等)可以被声明为隐式的,你可以猜到的,通过加上 "implicit" +// 关键字。请注意这些例子中,我们用到第5部分的 Dog 类。 +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// implicit 关键字本身不改变值的行为,所以上面的值可以照常使用。 +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" -val n = 45 -println(s"We have $n apples") +// 区别在于,当另一段代码“需要”隐式值时,这些值现在有资格作为隐式值。 +// 一种情况是隐式函数参数。 +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") +// 如果提供值给 “howMany”,函数正常运行 +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" -// 一些字符需要被转义,举例来说,字符串中的双引号: -val a = "They stood outside the \"Rose and Crown\"" +// 如果省略隐式参数,会传一个和参数类型相同的隐式值, +// 在这个例子中, 是 “myImplicitInt": +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" -// 三个双引号使得字符串可以跨行并且可以包含引号(无需转义) +// 隐式的函数参数使我们可以模拟其他函数式语言的 type 类(type classes)。 +// 它经常被用到所以有特定的简写。这两行代码是一样的: +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... -val html = """
-

Press belo', Joe

- | -
""" +// 编译器寻找隐式值另一种情况是你调用方法时 +// obj.method(...) +// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果存在一个将类型 A +// 转变为 B 的隐式转换,A 是 obj 的类型,B有一个叫 "method" 的方法,这样 +// 转换就会被应用。所以作用域里有上面的 myImplicitFunction, 我们可以这样做: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" +// 这里字符串先被上面的函数转换为 Dog 对象,然后调用合适的方法。 +// 这是相当强大的特性,但再次提醒,请勿轻率使用。 +// 事实上,当你定义上面的隐式函数时,编译器会作出警告,除非你真的了解 +// 你正在做什么否则不要使用。 -// 应用结果和组织 +///////////////////////////////////////////////// +// 9. 杂项 +///////////////////////////////////////////////// -// import +// 导入类 import scala.collection.immutable.List -// Import 所有的子包 +// 导入所有子包 import scala.collection.immutable._ -// 在一条语句中 Import 多个类 +// 一条语句导入多个类 import scala.collection.immutable.{List, Map} -// 使用 '=>' 来重命名一个 import +// 使用 ‘=>’ 对导入进行重命名 import scala.collection.immutable.{ List => ImmutableList } -// import 除了一些类的其它所有的类。下面的例子除去了 Map 类和 Set 类: +// 导入所有类,排除其中一些。下面的语句排除了 Map 和 Set: import scala.collection.immutable.{Map => _, Set => _, _} -// 在 scala 源文件中,你的程序入口点使用一个拥有单一方法 main 的对象来定义: - +// 在 Scala 文件用 object 和单一的 main 方法定义程序入口: object Application { def main(args: Array[String]): Unit = { // stuff goes here. } } -// 文件可以包含多个类和对象。由 scalac 来编译 +// 文件可以包含多个 class 和 object,用 scalac 编译源文件 -// 输入和输出 +// 输入输出 -// 一行一行读取文件 +// 按行读文件 import scala.io.Source -for(line <- Source.fromPath("myfile.txt").getLines()) +for(line <- Source.fromFile("myfile.txt").getLines()) println(line) -// 使用 Java 的 PrintWriter 来写文件 - +// 用 Java 的 PrintWriter 写文件 +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() ``` -- cgit v1.2.3 From 8f0027683d316d0b614be8841a76453fb4cfb347 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Wed, 15 Apr 2015 18:09:34 +0800 Subject: Some bug fixes. --- zh-cn/c++-cn.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index eed20721..46a34141 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -535,7 +535,7 @@ failure: } // 如果用异常捕获机制来指示错误的话, -// 代码会变得清晰一些,但是仍然有优化的餘地。 +// 代码会变得清晰一些,但是仍然有优化的余地。 void doSomethingWithAFile(const char* filename) { FILE* fh = fopen(filename, "r"); // 以只读模式打开文件 @@ -548,7 +548,7 @@ void doSomethingWithAFile(const char* filename) } catch (...) { fclose(fh); // 保证出错的时候文件被正确关闭 - throw; // Then re-throw the exception. + throw; // 之后,重新抛出这个异常 } fclose(fh); // 关闭文件 @@ -573,7 +573,7 @@ void doSomethingWithAFile(const std::string& filename) // 1. 无论发生了什么情况,资源(此例当中是文件句柄)都会被正确关闭。 // 只要你正确使用了析构器,就_不会_因为忘记关闭句柄,造成资源的泄漏。 // 2. 可以注意到,通过这种方式写出来的代码十分简洁。 -// 析构器会在后臺关闭文件句柄,不再需要你来操心这些琐事。 +// 析构器会在后台关闭文件句柄,不再需要你来操心这些琐事。 // 3. 这种方式的代码具有异常安全性。 // 无论在函数中的何处拋出异常,都不会阻碍对文件资源的释放。 -- cgit v1.2.3 From 60b56e777efa1b5c24cf5104556a2eb7aa6fbed2 Mon Sep 17 00:00:00 2001 From: yejinchang Date: Wed, 15 Apr 2015 18:12:21 +0800 Subject: fix minor mistake --- zh-cn/scala-cn.html.markdown | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 5d5d93c7..f292271e 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -191,7 +191,7 @@ addOne(5) // => 6 weirdSum(2, 4) // => 16 -// return 关键字是存在的,但它从最里面包裹了 return 的 def 函数中返回。 +// return 关键字是存在的,但它只从最里面包裹了 return 的 def 函数中返回。 // 警告: 在 Scala 中使用 return 容易出错,应该避免使用。 // 在匿名函数中没有效果,例如: def foo(x: Int): Int = { @@ -304,13 +304,11 @@ s(1) (a, 2, "three") // 为什么有这个? - val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // 函数 divideInts 返回您结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 - val d = divideInts(10,3) d._1 @@ -360,7 +358,7 @@ println(mydog.bark) // => "Woof, woof!" // "object" 关键字创造一种类型和该类型的单例。 // Scala 的 class 常常也含有一个 “伴生对象”,class 中包含每个实例的行为,所有实例 -// 共用的行为则放入 object 中。两者的区别和其他语言中方法和静态方法类似。 +// 共用的行为则放入 object 中。两者的区别和其他语言中类方法和静态方法类似。 // 请注意 object 和 class 可以同名。 object Dog { def allKnownBreeds = List("pitbull", "shepherd", "retriever") @@ -374,14 +372,14 @@ object Dog { // 数据。它们通常只有几个方法,且方法几乎没有副作用。 case class Person(name: String, phoneNumber: String) -// 创造新实例,注意 case 类不需要 "new" 关键字 +// 创造新实例,注意 case 类不需要使用 "new" 关键字 val george = Person("George", "1234") val kate = Person("Kate", "4567") // 使用 case 类,您可以轻松得到一些功能,像 getters: george.phoneNumber // => "1234" -// 每个字段的相等性(无需覆盖 .equals) +// 每个字段的相等性比较(无需覆盖 .equals) Person("George", "1234") == Person("Kate", "1236") // => false // 简单的拷贝方式 @@ -412,7 +410,7 @@ def matchPerson(person: Person): String = person match { val email = "(.*)@(.*)".r // 定义下一个例子会用到的正则 // 模式匹配看起来和 C语言家族的 switch 语句相似,但更为强大。 -// Scala 中您可以很多东西: +// Scala 中您可以匹配很多东西: def matchEverything(obj: Any): String = obj match { // 匹配值: case "Hello world" => "Got the string Hello world" -- cgit v1.2.3 From 4adbf231c805afdf68fed3a5e2aba9c90fd4c0c1 Mon Sep 17 00:00:00 2001 From: yejinchang Date: Thu, 16 Apr 2015 17:53:40 +0800 Subject: make corrections --- zh-cn/scala-cn.html.markdown | 39 ++++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 19 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index f292271e..343982ff 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -8,10 +8,11 @@ contributors: translators: - ["Peiyong Lin", ""] - ["Jinchang Ye", "http://github.com/alwayswithme"] + - ["Guodong Qu", "https://github.com/jasonqu"] lang: zh-cn --- -Scala - 一门可拓展性的语言 +Scala - 一门可拓展的语言 ```scala @@ -103,7 +104,7 @@ true == false // false 'a' // Scala 的字符 // '不存在单引号字符串' <= 这会导致错误 -// 字符串定义了常见的 Java 方法 +// String 有常见的 Java 字符串方法 "hello world".length "hello world".substring(2, 6) "hello world".replace("C", "3") @@ -174,14 +175,14 @@ addWithDefault(1) // => 6 // 匿名函数是这样的: (x:Int) => x * x -// 和 def 不同,如果语义清晰,匿名函数的输入类型也可以省略。 +// 和 def 不同,如果语义清晰,匿名函数的参数类型也可以省略。 // 类型 "Int => Int" 意味着这个函数接收一个 Int 并返回一个 Int。 val sq: Int => Int = x => x * x // 匿名函数的调用也是类似的: sq(10) // => 100 -// 如果您的匿名函数有一到两个参数,每一个参数仅使用一次, +// 如果您的匿名函数中每个参数仅使用一次, // Scala 提供一个更简洁的方式来定义他们。这样的匿名函数极为常见, // 在数据结构部分会明显可见。 val addOne: Int => Int = _ + 1 @@ -221,7 +222,7 @@ val r = 1 to 5 r.foreach( println ) r foreach println -// 留意: Scala 对点和括号的要求比较宽松,对这些规则加以区分。 +// 附注: Scala 对点和括号的要求想当宽松,注意其规则是不同的。 // 这有助于写出读起来像英语的 DSL(领域特定语言) 和 API(应用编程接口)。 (5 to 1 by -1) foreach ( println ) @@ -306,7 +307,7 @@ s(1) // 为什么有这个? val divideInts = (x:Int, y:Int) => (x / y, x % y) -divideInts(10,3) // 函数 divideInts 返回您结果和余数 +divideInts(10,3) // 函数 divideInts 同时返回结果和余数 // 要读取元组的元素,使用 _._n,n是从1开始的元素索引 val d = divideInts(10,3) @@ -322,9 +323,9 @@ d._2 /* 旁白: 教程中到现在为止我们所做的一切只是简单的表达式(值,函数等)。 - 这些表达示可以输入到命令行解释器中作为快速测试,但它们无法单一的存在于 Scala - 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。而 Scala 允许存 - 在的顶级结构是: + 这些表达式可以输入到命令行解释器中作为快速测试,但它们不能独立存在于 Scala + 文件。举个例子,您不能在 Scala 文件上简单的写上 "val x = 5"。相反 Scala 文件 + 允许的顶级结构是: - objects - classes @@ -346,7 +347,7 @@ class Dog(br: String) { private def sleep(hours: Int) = println(s"I'm sleeping for $hours hours") - // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类需要被声明为 abstract + // 抽象方法是没有方法体的方法。如果取消下面那行注释,Dog 类必须被声明为 abstract // abstract class Dog(...) { ... } // def chaseAfter(what: String): String } @@ -397,7 +398,7 @@ val otherGeorge = george.copy(phoneNumber = "9876") ///////////////////////////////////////////////// // 模式匹配是一个强大和常用的 Scala 特性。这是用模式匹配一个 case 类的例子。 -// 留意:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 +// 附注:不像其他语言, Scala 的 case 不需要 break, 其他语言中 switch 语句的 // fall-through 现象不会发生。 def matchPerson(person: Person): String = person match { @@ -457,7 +458,7 @@ List(1, 2, 3) map add10 // List(11, 12, 13) - add10 被应用到每一个元素 // 匿名函数可以被使用来代替有命名的函数: List(1, 2, 3) map (x => x + 10) -// 下划线标志,如果匿名函数只有一个参数可以被使用来表示该参数变量 +// 如果匿名函数只有一个参数可以用下划线作为变量 List(1, 2, 3) map (_ + 10) // 如果您所应用的匿名块和匿名函数都接受一个参数,那么你甚至可以省略下划线 @@ -475,7 +476,7 @@ sSquared.filter(_ < 10) sSquared.reduce (_+_) -// filter 函数接受一个 predicate (函数从 A -> Boolean)并选择 +// filter 函数接受一个 predicate (函数根据条件 A 返回 Boolean)并选择 // 所有满足 predicate 的元素 List(1, 2, 3) filter (_ > 2) // List(3) case class Person(name:String, age:Int) @@ -514,8 +515,8 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared * 就不可能做有意义的事情。这章节主要让你理解和使用隐式转换,而不是自己声明。 */ -// 任何值(val, 函数,对象等)可以被声明为隐式的,你可以猜到的,通过加上 "implicit" -// 关键字。请注意这些例子中,我们用到第5部分的 Dog 类。 +// 可以通过 "implicit" 声明任何值(val, 函数,对象等)为隐式值, +// 请注意这些例子中,我们用到第5部分的 Dog 类。 implicit val myImplicitInt = 100 implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) @@ -542,13 +543,13 @@ def foo[T : C] = ... // 编译器寻找隐式值另一种情况是你调用方法时 // obj.method(...) -// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果存在一个将类型 A -// 转变为 B 的隐式转换,A 是 obj 的类型,B有一个叫 "method" 的方法,这样 +// 但 "obj" 没有一个名为 "method" 的方法。这样的话,如果有一个参数类型为 A +// 返回值类型为 B 的隐式转换,obj 的类型是 A,B 有一个方法叫 "method" ,这样 // 转换就会被应用。所以作用域里有上面的 myImplicitFunction, 我们可以这样做: "Retriever".breed // => "Golden Retriever" "Sheperd".bark // => "Woof, woof!" -// 这里字符串先被上面的函数转换为 Dog 对象,然后调用合适的方法。 +// 这里字符串先被上面的函数转换为 Dog 对象,然后调用相应的方法。 // 这是相当强大的特性,但再次提醒,请勿轻率使用。 // 事实上,当你定义上面的隐式函数时,编译器会作出警告,除非你真的了解 // 你正在做什么否则不要使用。 @@ -585,7 +586,7 @@ object Application { -// 输入输出 +// 输入和输出 // 按行读文件 import scala.io.Source -- cgit v1.2.3 From c8c6924dccf3184b0c2c60226291de3cae4c1380 Mon Sep 17 00:00:00 2001 From: alwayswithme Date: Fri, 17 Apr 2015 14:55:01 +0800 Subject: resolve translation errors --- zh-cn/scala-cn.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/scala-cn.html.markdown b/zh-cn/scala-cn.html.markdown index 343982ff..508dd58e 100644 --- a/zh-cn/scala-cn.html.markdown +++ b/zh-cn/scala-cn.html.markdown @@ -97,7 +97,7 @@ true == false // false 这意味着计算 1 + 7 的结果是一个 Int 类型的对象,其值为 8 注意 "res29" 是一个连续生成的变量名,用以存储您输入的表达式结果, - 您看到的输入可能不一样。 + 您看到的输出可能不一样。 */ "Scala strings are surrounded by double quotes" @@ -486,7 +486,9 @@ List( ).filter(_.age > 25) // List(Person("Bob", 30)) -// Scala 的 foreach 方法定义在特定集合中,接受一个类型并返回 Unit (void 方法) +// Scala 的 foreach 方法定义在某些集合中,接受一个函数并返回 Unit (void 方法) +// 另请参见: +// http://www.scala-lang.org/api/current/index.html#scala.collection.IterableLike@foreach(f:A=>Unit):Unit val aListOfNumbers = List(1, 2, 3, 4, 10, 20, 100) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println -- cgit v1.2.3 From c5212932b9e7fb2d42eb74049877488678b85967 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Fri, 17 Apr 2015 22:19:13 +0800 Subject: More bug fixes. --- zh-cn/c++-cn.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index 46a34141..e5c5d5df 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -282,7 +282,7 @@ public: void bark() const { std::cout << name << " barks!\n" } // 除了构造器以外,C++还提供了析构器。 - // 当一个对象被删除或者脱离其定义域时时,它的析构函数会被调用。 + // 当一个对象被删除或者脱离其定义域时,它的析构函数会被调用。 // 这使得RAII这样的强大范式(参见下文)成为可能。 // 为了衍生出子类来,基类的析构函数必须定义为虚函数。 virtual ~Dog(); @@ -353,7 +353,7 @@ class OwnedDog : public Dog { // 重写OwnedDogs类的print方法。 // 如果你不熟悉子类多态的话,可以参考这个页面中的概述: - // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping + // http://zh.wikipedia.org/wiki/%E5%AD%90%E7%B1%BB%E5%9E%8B // override关键字是可选的,它确保你所重写的是基类中的方法。 void print() const override; -- cgit v1.2.3 From 7bab2c5e8d0301ca3480cbac92ecee99233f6677 Mon Sep 17 00:00:00 2001 From: Arnie97 Date: Fri, 17 Apr 2015 22:51:02 +0800 Subject: Remove duplicate code. --- zh-cn/c++-cn.html.markdown | 18 ------------------ 1 file changed, 18 deletions(-) (limited to 'zh-cn') diff --git a/zh-cn/c++-cn.html.markdown b/zh-cn/c++-cn.html.markdown index e5c5d5df..e1551e2b 100644 --- a/zh-cn/c++-cn.html.markdown +++ b/zh-cn/c++-cn.html.markdown @@ -289,8 +289,6 @@ public: }; // 在类的定义之后,要加一个分号 -}; // 记住,在类的定义之后,要加一个分号! - // 类的成员函数通常在.cpp文件中实现。 void Dog::Dog() { @@ -309,22 +307,6 @@ void Dog::setWeight(int dogsWeight) weight = dogsWeight; } -// 虚函数的virtual关键字只需要在声明时使用,不需要在定义时出现 -void Dog::print() const -{ - std::cout << "Dog is " << name << " and weighs " << weight << "kg\n"; -} - -void Dog::~Dog() -{ - cout << "Goodbye " << name << "\n"; -} - -void Dog::setWeight(int dogsWeight) -{ - weight = dogsWeight; -} - // 虚函数的virtual关键字只需要在声明时使用,不需要在定义时重复 void Dog::print() const { -- cgit v1.2.3