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/c++-cn.html.markdown') 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/c++-cn.html.markdown') 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/c++-cn.html.markdown') 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 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/c++-cn.html.markdown') 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/c++-cn.html.markdown') 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 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/c++-cn.html.markdown') 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 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/c++-cn.html.markdown') 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/c++-cn.html.markdown') 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