You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Cplusplus.md 17 KiB

4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. **Under construction.**
  2. \'\'If you have any problems with this tutorial or want to give
  3. feedback, ask questions or get additional help, please e-mail
  4. coconut<at>redbrick<dot>dcu<dot>ie or, for general
  5. [Helpdesk](/Helpdesk "wikilink") queries,
  6. helpdesk<at>redbrick<dot>dcu<dot>ie. \'\'
  7. **C++** is an object-oriented programming language, developed as a
  8. superset of the language [C](/C "wikilink"), which means that the
  9. language is essentially C with more features, hence the name. However,
  10. it has since evolved into a separate language and compatibility with C
  11. is no longer guaranteed.
  12. It is a very popular all-purpose language which is commonly utilised for
  13. game programming, and in many respects is quite similar to
  14. [Java](/Java "wikilink"), another object-oriented language.
  15. ## g++
  16. The page [Programming On Redbrick](/Programming_On_Redbrick "wikilink")
  17. explains how to compile programs written in C++. Here we will go into
  18. more depth as to how the compiler g++ works.
  19. A compiler works by translating your programming language (in this case,
  20. C++) into machine code, which is the basic language that a processor
  21. understands. While C++ is a universal language (source code written on
  22. one architecture will generally work on another unless special libraries
  23. are used), programs must be recompiled if they are to be used on
  24. different architectures - for example, if you are compiling on murphy,
  25. which uses the UltraSPARC architecture, you will have to recompile your
  26. program if you wish to use it on carbon or deathray, which use the Intel
  27. x86 architecture, because UltraSPARC and x86 assembly languages are
  28. completely different.
  29. g++ is the free, open-source C++ compiler which is included with many
  30. distributions of Linux as part of the gcc package, the latter of which
  31. is a C compiler. Other popular C++ compilers include Borland C++ and
  32. Microsoft Visual C++, however these are proprietary. gcc (and g++) is
  33. the most widely ported and universally available compiler in the world.
  34. ## Getting started
  35. To begin programming in C++ on RedBrick, you first have to log in. Once
  36. you\'ve done that, you can create a new folder for your C++ files by
  37. utilising the following command
  38. `mkdir C++`
  39. This will create a directory called \"C++\" in your home directory.
  40. Enter this directory by typing
  41. `cd C++`
  42. Now you\'re ready to create your first C++ program. For this tutorial,
  43. we are going to use the [nano](/nano "wikilink") editor. Make a new C++
  44. source file, that we will call \"first\", with
  45. `nano first.cpp`
  46. C++ source code files will generally use the .cpp extension - you may
  47. have noticed that C programs use .c
  48. nano should be open, awaiting input. The first thing you should do is
  49. import the necessary libraries to allow input/output in your program.
  50. This is the only library we will use at this point. Make the following
  51. line 1 of your program
  52. `#include`<iostream>
  53. **iostream** (or, archaically, iostream.h) is a C++ header file, which
  54. is a file containing C++ code designed to be imported by multiple
  55. programs.
  56. Now we want to create our **main()** function. main() is the first part
  57. of code that will be executed upon running your program. main() will
  58. typically look something like this
  59. `int main()`\
  60. `{`\
  61. `// insert some code here`\
  62. ``\
  63. `return(0);`\
  64. `}`
  65. There are a couple of things that have to be explained here.
  66. * The function begins with **int** - an int in C++ means integer,
  67. which is simply a type of variable - in this case a number. Having
  68. the function declaration as int main() means that the function
  69. main() will return an int at the end of its execution. main() will
  70. **always** return an int.
  71. <!-- -->
  72. * Chain brackets **{ }** are used to denote the code which main()
  73. contains. When you call main(), the code between these brackets will
  74. be executed.
  75. <!-- -->
  76. * **//** is used to make a comment. A comment is a line in your source
  77. code which will be completely ignored by the compiler. This is handy
  78. for explaining what your code does and you should quickly learn to
  79. use them frivilously.
  80. <!-- -->
  81. * **return(0);** is placed at the end of your main() function. The 0
  82. is the int which is returned by the function - in this case, 0 means
  83. the program executed without any problems. Yay!!! The ; is used to
  84. mark the end of a line where a command is issued. If you omit this
  85. semicolon, the compiler will whinge at you.
  86. So, at this point your program should look like this
  87. `#include`<iostream>\
  88. \
  89. `int main()`\
  90. `{`\
  91. `// insert some code here`\
  92. ``\
  93. `return(0);`\
  94. `}`
  95. The [Programming On Redbrick](/Programming_On_Redbrick "wikilink") page
  96. explains how to compile C++ programs. Just to recap, we\'ll go over it
  97. again (oh joy!) To indent your code as shown above, press TAB. (Proper
  98. indentation is essential programming practice.) Press CTRL+O to bring up
  99. the save option, enter to save and then CTRL+X to exit.
  100. `g++ -o first first.cpp`
  101. The -o parameter allows you to tell the compiler where you want to have
  102. the compiled program saved and what you want its name to be. In this
  103. case, it\'ll be compiled to the same folder as your source file,
  104. first.cpp
  105. Your program _should_ compile. If it does, run it by entering
  106. `./first`
  107. Nothing will happen. That\'s because we haven\'t told the program to do
  108. anything!
  109. ## Wow your ma with a basic program
  110. Open up your source file again and delete the comment line. Now it\'s
  111. time to get stuck into some real code.
  112. Change your program so it now reads
  113. `#include`<iostream>\
  114. \
  115. `int main()`\
  116. `{`\
  117. `std::cout << "This is my first real C++ program. Epic lulz!" << std::endl;`\
  118. ``\
  119. `return(0);`\
  120. `}`
  121. If you compile this, the program should execute and print this line onto
  122. the screen
  123. `This is my first real C++ program. Epic lulz!`
  124. Hurrah! Something useful and/or interesting!
  125. * **cout** is the C++ command for issuing an output. By default, this
  126. will go to the screen. Use left-facing arrow thingies (\<\<) to put
  127. your output into the cout command. You can link several things
  128. together by using multiple pairs of arrows as seen in the code,
  129. without having to issue cout twice.
  130. * **endl** moves output to the next line on the screen. It also
  131. flushes the stream\... whatever that means.
  132. * **std** is the namespace which contains cout and endl. We could
  133. include the entire namespace in the code, but for now we don\'t need
  134. to since we\'re only using two of its functions - therefore we\'ll
  135. access them directly by putting std:: in front of cout and endl.
  136. * The text between the \" \" is called a string of characters. In C++,
  137. strings are always put between inverted commas like this.
  138. To be updated later\...
  139. ## Variables and operators
  140. So, you\'ve created your first C++ program. You must be so proud of
  141. yourself. Here\'s where the **pain** begins. We\'re moving on to
  142. variables and operators.
  143. A variable is a data container which you assign a value and whose value
  144. can, by default, be changed during the execution of your program.
  145. That\'s why it\'s called a variable.
  146. In C++, there are four variable types which you will use most
  147. * **int** as explained earlier, is a number.
  148. * **char** is a single ASCII character - a letter, a number or a
  149. symbol.
  150. * **double** is a decimal (floating point) number, for example: 5.673
  151. or 1.0
  152. * **string** is just a string (array) of characters - you need to
  153. \#include the string library for this to work as a data type.
  154. There are other ones which you won\'t need as often
  155. * **short** is, depending on the compiler, a number whose bit length
  156. is shorter (or sometimes) equal to an int.
  157. * **long** has a bit length twice that of an int.
  158. * **float** is a decimal (floating point) with half the precision of a
  159. double - shit, in other words. Avoid unless you\'re running on a
  160. system with memory measured in kilobytes and desperately need to
  161. conserve space, like the [D6](/D6 "wikilink"). God help you.
  162. To initialise a variable such as an int, simply use the line
  163. `int a;`
  164. This reserves memory space for an int called a. But this isn\'t much
  165. good, is it? We need to give it a value. If you declare the variable
  166. like above, you can later assign a value like this
  167. `a = 5;`
  168. Now a has the value of 5, however, this is the n00bs\' way of doing it.
  169. Why not declare and assign at the same time?
  170. `int a = 5;`
  171. That\'s more like it. You\'ll be a RB admin in no time. Let\'s run
  172. through initialising other variables.
  173. `int a = 5;`\
  174. `double b = 10.463;`\
  175. `char c = 'H';`\
  176. `string d = "Warning: Haskell may contain traces of anti-lulz.";`
  177. Hopefully you\'re getting the idea. Now that we\'re using string, we
  178. will have to start using the namespace std in our code for the sake of
  179. speed. Because of this, you will notice the absence of std:: which may
  180. make things easier for you.
  181. We can throw the above code into a program and make it output the
  182. variables to the screen
  183. `#include`<iostream>\
  184. `#include`<string>`// Remember to include string if you're using a string!`\
  185. \
  186. `using namespace std; // Also remember this!`\
  187. \
  188. `int main()`\
  189. `{`\
  190. `int a = 5;`\
  191. `double b = 10.463;`\
  192. `char c = 'H';`\
  193. `string d = "Warning: Haskell may contain traces of anti-lulz.";`\
  194. ``\
  195. `cout << a << endl << b << endl << c << endl << d << endl;`\
  196. ``\
  197. `return(0);`\
  198. `}`
  199. Note how we can print four lines, with four different variables, using
  200. one cout command by having multiple \<\<
  201. Also, see how string uses inverted commas \" \" whereas char uses two
  202. apostrophes \' \' - this is called being unnecessary complicated. But at
  203. least this isn\'t Haskell, so cheer up.
  204. So, say you want to add two numbers together for some reason which makes
  205. sense to you. How? Simple. There are several ways to do it.
  206. `int a = 2;`\
  207. `int b = 6;`\
  208. `int c = a + b;`
  209. The value of c is now the values of a and b added together. If you
  210. don\'t want to bother with a third variable, you can just put the answer
  211. into a or b by replacing the third line with
  212. `a = a + b;`
  213. To output c to the screen
  214. `cout << c;`
  215. Or, without having to use c at all
  216. `cout << a + b;`
  217. This adds a and b together and outputs it to the screen all in one go.
  218. Hurrah!
  219. You can also add doubles together in the same fashion.
  220. Say you have a few chars and you want to combine them together in order
  221. to form a word, and then print it to the screen
  222. `char a = 'o';`\
  223. `char b = 'm';`\
  224. `char c = 'g';`\
  225. `char d = 'w';`\
  226. `char e = 'a';`\
  227. `char f = 'f';`\
  228. \
  229. `cout << a + b + c + d + e + f;`
  230. This will print \"omgwaf\" on the screen.
  231. Another way to do it, without using variables at all, is
  232. `cout << "omgwaf";`
  233. You can also waste everyone\'s RAMz if you want, by using a string for
  234. no justifiable reason. Say you\'ve already declared the chars and
  235. assigned their values
  236. `string rofl = a + b + c + d + e + f;`\
  237. \
  238. `cout << rofl;`
  239. Remember: a string is merely an array of characters so this works with
  240. strings too. You\'ll learn more about arrays later.
  241. There are other basic operators in C++.
  242. * **+** is the addition operator. It allows numbers to be added and
  243. chars and strings to be joined together.
  244. * **-** is the subtraction operator. With it you can subtract numbers.
  245. * **\*** is multiplication. Multiply numbers.
  246. * **/** is division. Divide numbers.
  247. Say you want C++ to do your maths homework for you because you feel
  248. Michael Clancy is going to fail you for being such a newb.
  249. `int a = (5 * ((12/3) - 1)) + 25`
  250. Easy as [undone](/undone "wikilink")\'s mother.
  251. This will divide 12 by 3, giving 4, then take 1 from it, giving 3,
  252. multiply that by 5, giving 15, and then add it to 25, resulting in 40,
  253. which is then assigned as the value for a. Try it yourself. Brackets are
  254. very handy for mathematical calculations in C++, just like in that yoke
  255. known as \"real life\".
  256. C++ can also handle negative numbers, just as you would expect a
  257. calculator to, except this time the calculator can run 32 threads
  258. simultaneously, is about one hundred times bigger, ten thousand times
  259. louder, needs several hundred watts of power to function and only the
  260. five richest kings of Europe can afford one.
  261. Perhaps that last part was slightly untrue.
  262. ## if statements and advanced operators
  263. A crucial element of any programming language is the ability to test
  264. whether something meets a defined condition. The most basic way of doing
  265. this in C++ is by using the **if** statement. Here\'s an example of how
  266. if and else work
  267. `#include`<iostream>\
  268. \
  269. `using namespace std;`\
  270. \
  271. `int main()`\
  272. `{`\
  273. `int a = 4;`\
  274. ``\
  275. `if(a == 5)`\
  276. `{`\
  277. `cout << "a is 5." << endl;`\
  278. `}`\
  279. `else if(a == 4)`\
  280. `{`\
  281. `cout << "a is 4" << endl;`\
  282. `}`\
  283. `else`\
  284. `{`\
  285. `cout << "a does not equal 4 or 5." << endl;`\
  286. `}`\
  287. \
  288. `return(0);`\
  289. `}`
  290. If is 5, the program will return \"a is 5.\", if it is 4, the program
  291. will return \"a is 4\". If it is neither 5 nor 4, the program will
  292. return \"a does not equal 4 or 5.\"
  293. You can use an infinite number of **else if** statements, linking ifs
  294. together, but it is probably bad programming practice to use too many.
  295. Also note that if you only have one line of code following an if, if
  296. else or else statement (the line which will be executed when the
  297. condition is satisfied), you _may_ omit the chain brackets for the
  298. statement.
  299. `if(a < 10)`\
  300. `cout << "a is less than 10." << endl;`
  301. If a is less than 10, the program will return \"a is less than 10.\"
  302. * **==** is used to see if two variables are equal. It will work for
  303. all data types except string, for which there are other functions
  304. dealt with later.
  305. * **!=** not equal to
  306. * **\<=** less than or equal to
  307. * **\>=** greater than or equal to
  308. * **\<** less than
  309. * **\>** greater than
  310. ## Loops
  311. Most programming languages support **loops**, which are useful for
  312. executing a certain part of code over and over.
  313. Here is a **while** loop
  314. `#include`<iostream>\
  315. \
  316. `using namespace std;`\
  317. \
  318. `int main()`\
  319. `{`\
  320. `int a = 0;`\
  321. \
  322. `while(a < 100)`\
  323. `{`\
  324. `cout << a << endl;`\
  325. `a++;`\
  326. `}`\
  327. \
  328. `return(0);`\
  329. `}`
  330. This will print 100 lines of numbers, going from 0 to 99
  331. `0`\
  332. `1`\
  333. `2`\
  334. `3`\
  335. `4`\
  336. `5`\
  337. `...`
  338. The condition to make sure that a is less than 100 is checked at the
  339. start of each loop, and a is incremented by 1 at the end of each loop
  340. (denoted by **a++**; you can also use **a\--** to decrement by 1).
  341. Therefore, when a reaches 99, it will be printed to screen, then
  342. incremented. The loop will then check to see if it is less than 100,
  343. which it is not, resulting in the termination of the loop.
  344. While loops are handy in games where you may want something to loop
  345. endlessly until the user makes an action (presses a key, for example).
  346. Here is a variation of the while loop, called the **do while** loop.
  347. `#include`<iostream>\
  348. \
  349. `using namespace std;`\
  350. \
  351. `int main()`\
  352. `{`\
  353. `int a = 0;`\
  354. \
  355. `do`\
  356. `{`\
  357. `cout << a << endl;`\
  358. `a++;`\
  359. `}`\
  360. `while(a < 100);`\
  361. \
  362. `return(0);`\
  363. `}`
  364. This print the same 100 lines, 0 to 99. However, the condition for the
  365. loop is not checked until the end of the loop.
  366. If you\'re dealing with finite numbers of loops, you may want to
  367. consider the **for loop**
  368. `#include`<iostream>\
  369. ``\
  370. `using namespace std;`\
  371. \
  372. `int main()`\
  373. `{`\
  374. `for(int a = 0; a < 100; a++)`\
  375. `{`\
  376. `cout << a << endl;`\
  377. `}`\
  378. \
  379. `return(0);`\
  380. `}`
  381. This produces the same result, except in a much handier format. There
  382. are three things you declare when creating a for loop: a variable, what
  383. condition must be met for the loop to continue cycling, and what happens
  384. at the end of a loop. a is the initialised variable, the loop will
  385. continue until it reaches 100 and at the end of each loop, a is
  386. incremented by 1. Simple.
  387. To end a loop immediately, issue the following command in your code
  388. `break;`
  389. For example, if you want the loop to end early when a certain condition
  390. is met, just use an if statement inside the loop and have the loop break
  391. if this condition is met.
  392. ## Executing system commands in C++
  393. It is possible to execute system commands from within your C++ program.
  394. If your program is command-line only, you can execute simple commands
  395. such as those to clear the screen, etc.
  396. If you\'re using Linux, the code is
  397. `system("clear");`
  398. You can also do this if you\'re running Windows (although why would you
  399. want to?) The DOS clear command is \"cls\"
  400. `system("cls");`
  401. \...like so!
  402. However, it is recommended that you **not** use system commands in your
  403. code for something as trivial as clearing the screen. It\'s a resource
  404. hog and leaves a gaping security hole in your C++ program. There is a
  405. better way to do this in C++, however it requires advanced knowledge of
  406. the language and is available below under _Advanced_.
  407. ## Functions: The Basics
  408. It\'s now time to move on to **functions**. A function is basically the
  409. same thing as a method in Java: it is a sequence of commands which can
  410. be called upon at any time, passed parameters and set to return a value.
  411. main() is a function - the default function for a C++ program. But what
  412. if you have some code that you don\'t want to put into main? Use another
  413. function.
  414. Let\'s say we want to add two numbers together and print out the result.
  415. The code could look something like this:
  416. `#include`<iostream>\
  417. \
  418. `using namespace std;`\
  419. \
  420. `int add(int a, int b)`\
  421. `{`\
  422. `return a + b;`\
  423. `}`\
  424. \
  425. `int main()`\
  426. `{`\
  427. `int a = 2;`\
  428. `int b = 5;`\
  429. \
  430. `cout << add(a,b) << endl;`\
  431. \
  432. `return(0);`\
  433. `}`
  434. This program adds 2 and 5 together to get 7, and displays this answer
  435. on-screen.
  436. a and b are passed as _parameters_ to the add function - they are then
  437. immediately added together and the answer is returned. Experiment with
  438. this code to do different things.
  439. ## More advanced C++
  440. I\'ll get around to this someday. I\'m still learning too you know!
  441. [Category:Helpdesk](/Category:Helpdesk "wikilink")