鱼C论坛

 找回密码
 立即注册
查看: 1775|回复: 2

[技术交流] C++快速学习入门教程

[复制链接]
发表于 2014-10-28 18:54:50 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
转自 http://learnxinyminutes.com/docs/c++/

源文件下载 learncpp.zip (5.39 KB, 下载次数: 29)



  1. //////////////////
  2. // Comparison to C
  3. //////////////////

  4. // C++ is _almost_ a superset of C and shares its basic syntax for
  5. // variable declarations, primitive types, and functions.
  6. // However, C++ varies in some of the following ways:

  7. // A main() function in C++ should return an int,
  8. // though void main() is accepted by most compilers (gcc, clang, etc.)
  9. // This value serves as the program's exit status.
  10. // See http://en.wikipedia.org/wiki/Exit_status for more information.
  11. int main(int argc, char** argv)
  12. {
  13.     // Command line arguments are passed in by argc and argv in the same way
  14.     // they are in C.
  15.     // argc indicates the number of arguments,
  16.     // and argv is an array of C-style strings (char*)
  17.     // representing the arguments.
  18.     // The first argument is the name by which the program was called.
  19.     // argc and argv can be omitted if you do not care about arguments,
  20.     // giving the function signature of int main()

  21.     // An exit status of 0 indicates success.
  22.     return 0;
  23. }

  24. // In C++, character literals are one byte.
  25. sizeof('c') == 1

  26. // In C, character literals are the same size as ints.
  27. sizeof('c') == sizeof(10)


  28. // C++ has strict prototyping
  29. void func(); // function which accepts no arguments

  30. // In C
  31. void func(); // function which may accept any number of arguments

  32. // Use nullptr instead of NULL in C++
  33. int* ip = nullptr;

  34. // C standard headers are available in C++,
  35. // but are prefixed with "c" and have no .h suffix.
  36. #include <cstdio>

  37. int main()
  38. {
  39.     printf("Hello, world!\n");
  40.     return 0;
  41. }

  42. ///////////////////////
  43. // Function overloading
  44. ///////////////////////

  45. // C++ supports function overloading
  46. // provided each function takes different parameters.

  47. void print(char const* myString)
  48. {
  49.     printf("String %s\n", myString);
  50. }

  51. void print(int myInt)
  52. {
  53.     printf("My int is %d", myInt);
  54. }

  55. int main()
  56. {
  57.     print("Hello"); // Resolves to void print(const char*)
  58.     print(15); // Resolves to void print(int)
  59. }

  60. /////////////////////////////
  61. // Default function arguments
  62. /////////////////////////////

  63. // You can provide default arguments for a function
  64. // if they are not provided by the caller.

  65. void doSomethingWithInts(int a = 1, int b = 4)
  66. {
  67.     // Do something with the ints here
  68. }

  69. int main()
  70. {
  71.     doSomethingWithInts();      // a = 1,  b = 4
  72.     doSomethingWithInts(20);    // a = 20, b = 4
  73.     doSomethingWithInts(20, 5); // a = 20, b = 5
  74. }

  75. // Default arguments must be at the end of the arguments list.

  76. void invalidDeclaration(int a = 1, int b) // Error!
  77. {
  78. }


  79. /////////////
  80. // Namespaces
  81. /////////////

  82. // Namespaces provide separate scopes for variable, function,
  83. // and other declarations.
  84. // Namespaces can be nested.

  85. namespace First {
  86.     namespace Nested {
  87.         void foo()
  88.         {
  89.             printf("This is First::Nested::foo\n");
  90.         }
  91.     } // end namespace Nested
  92. } // end namespace First

  93. namespace Second {
  94.     void foo()
  95.     {
  96.         printf("This is Second::foo\n")
  97.     }
  98. }

  99. void foo()
  100. {
  101.     printf("This is global foo\n");
  102. }

  103. int main()
  104. {
  105.     // Assume everything is from the namespace "Second"
  106.     // unless otherwise specified.
  107.     using namespace Second;

  108.     foo(); // prints "This is Second::foo"
  109.     First::Nested::foo(); // prints "This is First::Nested::foo"
  110.     ::foo(); // prints "This is global foo"
  111. }

  112. ///////////////
  113. // Input/Output
  114. ///////////////

  115. // C++ input and output uses streams
  116. // cin, cout, and cerr represent stdin, stdout, and stderr.
  117. // << is the insertion operator and >> is the extraction operator.

  118. #include <iostream> // Include for I/O streams

  119. using namespace std; // Streams are in the std namespace (standard library)

  120. int main()
  121. {
  122.    int myInt;

  123.    // Prints to stdout (or terminal/screen)
  124.    cout << "Enter your favorite number:\n";
  125.    // Takes in input
  126.    cin >> myInt;

  127.    // cout can also be formatted
  128.    cout << "Your favorite number is " << myInt << "\n";
  129.    // prints "Your favorite number is <myInt>"

  130.     cerr << "Used for error messages";
  131. }

  132. //////////
  133. // Strings
  134. //////////

  135. // Strings in C++ are objects and have many member functions
  136. #include <string>

  137. using namespace std; // Strings are also in the namespace std (standard library)

  138. string myString = "Hello";
  139. string myOtherString = " World";

  140. // + is used for concatenation.
  141. cout << myString + myOtherString; // "Hello World"

  142. cout << myString + " You"; // "Hello You"

  143. // C++ strings are mutable and have value semantics.
  144. myString.append(" Dog");
  145. cout << myString; // "Hello Dog"


  146. /////////////
  147. // References
  148. /////////////

  149. // In addition to pointers like the ones in C,
  150. // C++ has _references_.
  151. // These are pointer types that cannot be reassigned once set
  152. // and cannot be null.
  153. // They also have the same syntax as the variable itself:
  154. // No * is needed for dereferencing and
  155. // & (address of) is not used for assignment.

  156. using namespace std;

  157. string foo = "I am foo";
  158. string bar = "I am bar";


  159. string& fooRef = foo; // This creates a reference to foo.
  160. fooRef += ". Hi!"; // Modifies foo through the reference
  161. cout << fooRef; // Prints "I am foo. Hi!"

  162. fooRef = bar; // Error: references cannot be reassigned.

  163. const string& barRef = bar; // Create a const reference to bar.
  164. // Like C, const values (and pointers and references) cannot be modified.
  165. barRef += ". Hi!"; // Error, const references cannot be modified.

  166. //////////////////////////////////////////
  167. // Classes and object-oriented programming
  168. //////////////////////////////////////////

  169. // First example of classes
  170. #include <iostream>

  171. // Declare a class.
  172. // Classes are usually declared in header (.h or .hpp) files.
  173. class Dog {
  174.     // Member variables and functions are private by default.
  175.     std::string name;
  176.     int weight;

  177. // All members following this are public
  178. // until "private:" or "protected:" is found.
  179. public:

  180.     // Default constructor
  181.     Dog();

  182.     // Member function declarations (implementations to follow)
  183.     // Note that we use std::string here instead of placing
  184.     // using namespace std;
  185.     // above.
  186.     // Never put a "using namespace" statement in a header.
  187.     void setName(const std::string& dogsName);

  188.     void setWeight(int dogsWeight);

  189.     // Functions that do not modify the state of the object
  190.     // should be marked as const.
  191.     // This allows you to call them if given a const reference to the object.
  192.     // Also note the functions must be explicitly declared as _virtual_
  193.     // in order to be overridden in derived classes.
  194.     // Functions are not virtual by default for performance reasons.
  195.     virtual void print() const;

  196.     // Functions can also be defined inside the class body.
  197.     // Functions defined as such are automatically inlined.
  198.     void bark() const { std::cout << name << " barks!\n" }

  199.     // Along with constructors, C++ provides destructors.
  200.     // These are called when an object is deleted or falls out of scope.
  201.     // This enables powerful paradigms such as RAII
  202.     // (see below)
  203.     // Destructors must be virtual to allow classes to be derived from this one.
  204.     virtual ~Dog();

  205. }; // A semicolon must follow the class definition.

  206. // Class member functions are usually implemented in .cpp files.
  207. void Dog::Dog()
  208. {
  209.     std::cout << "A dog has been constructed\n";
  210. }

  211. // Objects (such as strings) should be passed by reference
  212. // if you are modifying them or const reference if you are not.
  213. void Dog::setName(const std::string& dogsName)
  214. {
  215.     name = dogsName;
  216. }

  217. void Dog::setWeight(int dogsWeight)
  218. {
  219.     weight = dogsWeight;
  220. }

  221. // Notice that "virtual" is only needed in the declaration, not the definition.
  222. void Dog::print() const
  223. {
  224.     std::cout << "Dog is " << name << " and weighs " << weight << "kg\n";
  225. }

  226. void Dog::~Dog()
  227. {
  228.     cout << "Goodbye " << name << "\n";
  229. }

  230. int main() {
  231.     Dog myDog; // prints "A dog has been constructed"
  232.     myDog.setName("Barkley");
  233.     myDog.setWeight(10);
  234.     myDog.printDog(); // prints "Dog is Barkley and weighs 10 kg"
  235.     return 0;
  236. } // prints "Goodbye Barkley"

  237. // Inheritance:

  238. // This class inherits everything public and protected from the Dog class
  239. class OwnedDog : public Dog {

  240.     void setOwner(const std::string& dogsOwner)

  241.     // Override the behavior of the print function for all OwnedDogs. See
  242.     // http://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping
  243.     // for a more general introduction if you are unfamiliar with
  244.     // subtype polymorphism.
  245.     // The override keyword is optional but makes sure you are actually
  246.     // overriding the method in a base class.
  247.     void print() const override;

  248. private:
  249.     std::string owner;
  250. };

  251. // Meanwhile, in the corresponding .cpp file:

  252. void OwnedDog::setOwner(const std::string& dogsOwner)
  253. {
  254.     owner = dogsOwner;
  255. }

  256. void OwnedDog::print() const
  257. {
  258.     Dog::print(); // Call the print function in the base Dog class
  259.     std::cout << "Dog is owned by " << owner << "\n";
  260.     // Prints "Dog is <name> and weights <weight>"
  261.     //        "Dog is owned by <owner>"
  262. }

  263. //////////////////////////////////////////
  264. // Initialization and Operator Overloading
  265. //////////////////////////////////////////

  266. // In C++ you can overload the behavior of operators such as +, -, *, /, etc.
  267. // This is done by defining a function which is called
  268. // whenever the operator is used.

  269. #include <iostream>
  270. using namespace std;

  271. class Point {
  272. public:
  273.     // Member variables can be given default values in this manner.
  274.     double x = 0;
  275.     double y = 0;

  276.     // Define a default constructor which does nothing
  277.     // but initialize the Point to the default value (0, 0)
  278.     Point() { };

  279.     // The following syntax is known as an initialization list
  280.     // and is the proper way to initialize class member values
  281.     Point (double a, double b) :
  282.         x(a),
  283.         y(b)
  284.     { /* Do nothing except initialize the values */ }

  285.     // Overload the + operator.
  286.     Point operator+(const Point& rhs) const;

  287.     // Overload the += operator
  288.     Point& operator+=(const Point& rhs);

  289.     // It would also make sense to add the - and -= operators,
  290.     // but we will skip those for brevity.
  291. };

  292. Point Point::operator+(const Point& rhs) const
  293. {
  294.     // Create a new point that is the sum of this one and rhs.
  295.     return Point(x + rhs.x, y + rhs.y);
  296. }

  297. Point& Point::operator+=(const Point& rhs)
  298. {
  299.     x += rhs.x;
  300.     y += rhs.y;
  301.     return *this;
  302. }

  303. int main () {
  304.     Point up (0,1);
  305.     Point right (1,0);
  306.     // This calls the Point + operator
  307.     // Point up calls the + (function) with right as its paramater
  308.     Point result = up + right;
  309.     // Prints "Result is upright (1,1)"
  310.     cout << "Result is upright (" << result.x << ',' << result.y << ")\n";
  311.     return 0;
  312. }

  313. /////////////////////
  314. // Exception Handling
  315. /////////////////////

  316. // The standard library provides a few exception types
  317. // (see http://en.cppreference.com/w/cpp/error/exception)
  318. // but any type can be thrown an as exception
  319. #include <exception>

  320. // All exceptions thrown inside the _try_ block can be caught by subsequent
  321. // _catch_ handlers.
  322. try {
  323.     // Do not allocate exceptions on the heap using _new_.
  324.     throw std::exception("A problem occurred");
  325. }
  326. // Catch exceptions by const reference if they are objects
  327. catch (const std::exception& ex)
  328. {
  329.   std::cout << ex.what();
  330. // Catches any exception not caught by previous _catch_ blocks
  331. } catch (...)
  332. {
  333.     std::cout << "Unknown exception caught";
  334.     throw; // Re-throws the exception
  335. }

  336. ///////
  337. // RAII
  338. ///////

  339. // RAII stands for Resource Allocation Is Initialization.
  340. // It is often considered the most powerful paradigm in C++,
  341. // and is the simple concept that a constructor for an object
  342. // acquires that object's resources and the destructor releases them.

  343. // To understand how this is useful,
  344. // consider a function that uses a C file handle:
  345. void doSomethingWithAFile(const char* filename)
  346. {
  347.     // To begin with, assume nothing can fail.

  348.     FILE* fh = fopen(filename, "r"); // Open the file in read mode.

  349.     doSomethingWithTheFile(fh);
  350.     doSomethingElseWithIt(fh);

  351.     fclose(fh); // Close the file handle.
  352. }

  353. // Unfortunately, things are quickly complicated by error handling.
  354. // Suppose fopen can fail, and that doSomethingWithTheFile and
  355. // doSomethingElseWithIt return error codes if they fail.
  356. // (Exceptions are the preferred way of handling failure,
  357. //  but some programmers, especially those with a C background,
  358. //  disagree on the utility of exceptions).
  359. // We now have to check each call for failure and close the file handle
  360. // if a problem occurred.
  361. bool doSomethingWithAFile(const char* filename)
  362. {
  363.     FILE* fh = fopen(filename, "r"); // Open the file in read mode
  364.     if (fh == nullptr) // The returned pointer is null on failure.
  365.         reuturn false; // Report that failure to the caller.

  366.     // Assume each function returns false if it failed
  367.     if (!doSomethingWithTheFile(fh)) {
  368.         fclose(fh); // Close the file handle so it doesn't leak.
  369.         return false; // Propagate the error.
  370.     }
  371.     if (!doSomethingElseWithIt(fh)) {
  372.         fclose(fh); // Close the file handle so it doesn't leak.
  373.         return false; // Propagate the error.
  374.     }

  375.     fclose(fh); // Close the file handle so it doesn't leak.
  376.     return true; // Indicate success
  377. }

  378. // C programmers often clean this up a little bit using goto:
  379. bool doSomethingWithAFile(const char* filename)
  380. {
  381.     FILE* fh = fopen(filename, "r");
  382.     if (fh == nullptr)
  383.         reuturn false;

  384.     if (!doSomethingWithTheFile(fh))
  385.         goto failure;

  386.     if (!doSomethingElseWithIt(fh))
  387.         goto failure;

  388.     fclose(fh); // Close the file
  389.     return true; // Indicate success

  390. failure:
  391.     fclose(fh);
  392.     return false; // Propagate the error
  393. }

  394. // If the functions indicate errors using exceptions,
  395. // things are a little cleaner, but still sub-optimal.
  396. void doSomethingWithAFile(const char* filename)
  397. {
  398.     FILE* fh = fopen(filename, "r"); // Open the file in read mode
  399.     if (fh == nullptr)
  400.         throw std::exception("Could not open the file.");

  401.     try {
  402.         doSomethingWithTheFile(fh);
  403.         doSomethingElseWithIt(fh);
  404.     }
  405.     catch (...) {
  406.         fclose(fh); // Be sure to close the file if an error occurs.
  407.         throw; // Then re-throw the exception.
  408.     }

  409.     fclose(fh); // Close the file
  410.     // Everything succeeded
  411. }

  412. // Compare this to the use of C++'s file stream class (fstream)
  413. // fstream uses its destructor to close the file.
  414. // Recall from above that destructors are automatically called
  415. // whenver an object falls out of scope.
  416. void doSomethingWithAFile(const std::string& filename)
  417. {
  418.     // ifstream is short for input file stream
  419.     std::ifstream fh(filename); // Open the file

  420.     // Do things with the file
  421.     doSomethingWithTheFile(fh);
  422.     doSomethingElseWithIt(fh);

  423. } // The file is automatically closed here by the destructor

  424. // This has _massive_ advantages:
  425. // 1. No matter what happens,
  426. //    the resource (in this case the file handle) will be cleaned up.
  427. //    Once you write the destructor correctly,
  428. //    It is _impossible_ to forget to close the handle and leak the resource.
  429. // 2. Note that the code is much cleaner.
  430. //    The destructor handles closing the file behind the scenes
  431. //    without you having to worry about it.
  432. // 3. The code is exception safe.
  433. //    An exception can be thrown anywhere in the function and cleanup
  434. //    will still occur.

  435. // All idiomatic C++ code uses RAII extensively for all resources.
  436. // Additional examples include
  437. // - Memory using unique_ptr and shared_ptr
  438. // - Containers - the standard library linked list,
  439. //   vector (i.e. self-resizing array), hash maps, and so on
  440. //   all automatically destroy their contents when they fall out of scope.
  441. // - Mutexes using lock_guard and unique_lock
复制代码



小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

头像被屏蔽
发表于 2014-10-30 18:46:05 | 显示全部楼层
提示: 作者被禁止或删除 内容自动屏蔽
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 0 反对 1

使用道具 举报

发表于 2014-12-17 22:02:14 | 显示全部楼层

ThanksFORshare
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-18 10:55

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表