Hello, World

1
2
3
4
5
6
7
8
#include <iostream>
#include "console.h"
using namespace std;

int main() {
cout << "Hello, World!" << endl;
return 0;
}

C++的两种注释风格

块注释

块注释: 输入 /* ,之后所有的内容都被视为注释,直到遇到 */

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* This is a comment!
* This is also part of the same comment!
* Qt Creator adds a star on each line for formatting purposes when we use this
* type of comment.
Even though we don't have a star at the beginning of this line, it's still part of
our comment!
* When we hit the end of this line, the star-slash causes our comment to end. */

#include <iostream>
#include "console.h"
using namespace std;

int main()
{
cout << "Hello, world!" << endl;
return 0;
}

单行注释

单行注释: 输入 //,之后所有的内容都被视为注释,直到该行的末尾。

1
2
3
4
5
6
7
8
9
10
11
// This is a comment!
// This is a comment, too, but the line below this one is not!
#include <iostream>
#include "console.h"
using namespace std;

int main()
{
cout << "Hello, world!" << endl; // This is a comment, too!
return 0;
}

过度注释警告

  • 请考虑为你的不能从名称立即得到明确含义的任何函数编写高层概述,其中包括输入参数、预期输出和返回值。
  • 不要为每一行代码进行注释,避免简单重复代码中显而易见的内容,优选解释如何/为什么某事起作用的注释。
  • 尝试使用动词短语作函数名,这样可以作为代码功能的文档。
  • 保持注释简洁,除了在复杂的源文件顶部编写注释或者记录复杂的函数。
  • 假设你加载了五年后的一个作业的代码,但你丢失了那个作业的说明。什么样的注释会帮助你快速理解你用这些函数做了什么?
  • 如果你发现自己在某个时刻真的很难修复代码中的某个错误,那可能意味着你找到了一段复杂的代码,如果它有简洁的注释,那么它会更清晰。

#include指令

在 c++ 中使用 #include 语句来导入预先编写的代码库。

  • 包含标准系统库
1
#include <iostream>
  • 包含用户自定义的库
1
#include "LIBRARY_NAME"

#include 语句不以分号结尾,c++ 将读取这些语句直到行尾。

namespace

当我们在编写大型软件项目时,经常从不同来源导入多个库,而很有可能某些库中存在彼此同名的函数从而引发问题。

c++ 使用命名空间来处理这个问题,命名空间是分组在一起的函数的命名集合。

网络库可能会有一个 net 命名空间。

数据库可能会有一个 db 命名空间。

当我们调用网络库和数据库的 crateConnection() 函数时。

1
2
net::createConnection();
db::createConnection();

main() function

在数学界,函数主要完成三件事。

  1. 它需要一个输入值(某些情况下,需要多个输入值)。
  2. 它做了一些工作,例如,函数 $f(x)=x^2$ 将 $x$ 乘以自身。
  3. 它输出一个结果。如,上面定义的 $f(x)$,$f(5)$ 生成的结果是 25 。

c++ 中的函数也在做同样的事情。

1
2
3
DATA_TYPE FUNCTION_NAME (PARAMETERS) {
STATEMENT(S);
}
  • 在 c++ 中使用代码块(一组封装代码行的左花括号和右花括号)来表示构成某个函数的主体。
  • 为了您的阅读体验,请为代码保持良好的间距。

特殊的main函数

c++代码编译器逐行浏览我们编写的代码,从第一行一直往下,而执行总是从 main() 开始。

返回语句

从函数返回值的语法如下:

1
return EXPRESSION;

该表达式可以是任何计算为函数的适当返回类型的表达式,包括变量算术运算硬编码值其它函数调用

对 main() 函数而言,成功执行程序,main() 应始终返回 0 。如果有时返回的是非 0 值,表明程序没有完成我们想要完成的任务。

cout

我们将 cout 称为流,默认情况下我们使用 << 运算符发送给它的任何内容都会输出到屏幕上。

endl

endl 会在输出文本后面追加一个换行符(\n),并且刷新输出缓冲区,强制将缓冲区中的内容写入目标设备。

变量和数据类型

c++要求为使用的每个变量指定特定的数据类型,并且在声明之后不允许再更改。以下是 c++ 的数据类型表:

data type keywordtype descriptionexample(s)
intinteger(whole number)-3, 0, 1, 1051
floatfloating point number(real number)3.14159
doublefloating point number(real number)3.14159
charcharacter(single glyph)‘q’, ‘P’, ‘$’(requires single quotes)
stringstring of characters“Hello,world!”(requires double quotes)
boolBooleantrue, false(no quotes)

声明变量的语法:

1
DATA_TYPE VARIABLE_NAME;

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include "console.h"
using namespace std;

int main()
{
int a = 5;
char ch = 'q';
float f = 3.14159;
double d = 3.14159;
string s = "hello";

cout << "Hello, world!" << " " << a << endl;
cout << ch << " " << f << " " << d << endl;
cout << s << endl;

return 0;
}

变量使用的一些常见错误

  • 变量未声明

我们不能使用尚未声明的变量。该代码将无法编译。

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include "console.h"
using namespace std;

int main() {
a = 5; // ERROR: a is undeclared; we must give it a data type

cout << a << endl;
return 0;
}
  • 类型匹配

a 被设计为保存整数。我们不能将其设置为等于字符串。

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int a = 5;
a = "hello"; // ERROR: type mismatch; a can hold an integer, not a string

cout << a << endl;
return 0;
}
  • 尝试更改变量的数据类型

一旦变量被声明为某种类型,就不能用不同的类型重新声明它。

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int a = 5;
string a = "hello"; // ERROR: a is already declared; cannot declare with new type

cout << a << endl;
return 0;
}
  • 重新定义变量
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int a = 5;
int a = 7; // ERROR: a is already declared on the line above

cout << a << endl;
return 0;
}

如果您想更改已声明的变量的值,只需在另一行执行此操作,而无需重新声明数据类型:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int a = 5;
a = 7; // OKAY

cout << a << endl;
return 0;
}

变量未初始化

在 C++ 中,变量不会自动初始化。默认情况下,如果不给变量赋值,它就会包含垃圾。

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int a;
int b;
int c;

cout << a << " " << b << " " << c << endl; // YIKES. Uninitialized variables
// some compilers will let this compile despite the uninitialized variables!
return 0;
}

while 循环

while 循环的语法:

1
2
3
while ( CONDITION ) {
STATEMENT(S);
}

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int i = 5;

while (i < 5) {
cout << i << endl;
i++;
}

return 0;
}

++运算符

在 c++ 中可以使用 i++ 代替 i += 1

for循环

for循环的语法:

1
2
3
for ( INITIALIZATION_STATEMENT ;  CONDITION ;  POST_ITERATION_STATEMENT ) {
STATEMENT(S);
}

初始化语句仅执行一次(当我们首次进入for循环时),在开始迭代之前评估条件,并且在每次循环迭代结束时执行后增量语句,重新评估循环条件。

example:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "console.h"
using namespace std;

int main() {
for (int i = 1; i < 5; i++) {
cout << i << endl;
}

return 0;
}

for-each循环

c++提供的第三种循环,非常适合循环遍历容器中的所有元素。(例如:字符串中的所有字符或数组中的所有元素)

for-each 语法:

1
2
3
for (DATA_TYPE; VARIABLE_NAME : CONTAINER) {
STATEMENT(S);
}

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include "console.h"
using namespace std;

int main() {
string s = "giraffe";

// Initially, ch is set equal to the first character in s. With each subsequent
// iteration of the loop, ch moves forward by one character in the string.
for (char ch : s) {
cout << ch << endl;
}

return 0;
}

if语句和比较运算符

if语句语法:

1
2
3
if (CONDITION {
STATEMENT(S;
}

example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int numCupcakes = 5;

if (numCupcakes == 1) {
cout << "Oh no! Running low!" << endl;
} else if (numCupcakes > 1) {
cout << "Hooray, cupcakes!" << endl;
} else {
cout << "Oh nooOoOoOOoo!" << endl;
}

return 0;
}

c++ 中的比较运算符有:

operatormeaning
<less than
<=less than or equal to
>greater than
>=greater than or equal to
==equal to
!=not equal to

布尔运算符

operatormeaning
!Boolean “not”
&&Boolean “and”
\\Boolean “or”

||的常见操作错误

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "console.h"
using namespace std;

int main() {
int numCupcakes = 5;

// if (numCupcakes == 1 || 2) { // c++认为 2 为true
if (numCupcakes == 1 || numCupcakes == 2) // Fixed
cout << "Uh oh! We're running low on cupcakes!" << endl;
}

return 0;
}

void函数

如何函数不带参数,只需将括号内的参数列表留空即可。如果我们不需要它返回任何值,为函数指定返回类型 void 。

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include "console.h"
using namespace std;

void greet() {
cout << "hello :)" << endl;
}

int main() {
greet();
return 0;
}

函数传递参数和指定值

将返回值打印到屏幕上有两种方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include "console.h"
using namespace std;

// We pass an integer to this function, and it returns an integer.
int square(int x) {
return x * x;
}

int main() {
// Option1: Send the return value of square(5) directly to cout.
cout << square(5) << endl;

// Option2: Store the return value in a variable and print that.
int result = square(5);
cout << result << endl;

return 0;
}

函数定义与函数原型

函数原型: 带有分号的函数签名。函数签名是函数定义的第一行,它给出了返回类型、函数名称和参数列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "console.h"

using namespace std;

// 函数原型
int square(int x);

int main() {
cout << square(5) << endl; // This is okay now.
return 0;
}

// 函数定义
int square(int x) {
return x * x;
}

变量范围

  • 变量仅存在于声明他们的代码块中